# Generating Telegram Init Data

This project includes a helper script to generate valid, signed `initData` strings for testing. This is essential for simulating Telegram authentication during backend API testing or local frontend development without the actual Telegram app.

## Script Location
`scripts/generate_telegram_init_data.py`

## Prerequisites
- A valid `TELEGRAM_BOT_TOKEN` must be set in your backend `.env` file.
- Python environment with project dependencies installed.

## Usage

### 1. Load Environment Variables
The script needs access to `TELEGRAM_BOT_TOKEN` which is typically stored in `backend/.env`. You must load this into your shell session first.

```bash
cd backend
set -a; source .env; set +a
cd ..
```

### 2. Run the Script
Now run the script from the project root:

```bash
python scripts/generate_telegram_init_data.py [OPTIONS]
```

### Options

| Option | Description | Default |
|--------|-------------|---------|
| `--user-id` | Information for the mock user ID | `12345` |
| `--first-name` | First name of the mock user | `Test User` |
| `--username` | Username of the mock user | `testuser` |
| `--start-param` | Referral code or start parameter | `None` |

### Examples

**1. Basic Usage (Default User)**
```bash
python scripts/generate_telegram_init_data.py
```
*Output: Signed initData string for user ID 12345.*

**2. Custom User**
```bash
python scripts/generate_telegram_init_data.py --user-id 99999 --first-name "Alice" --username "alice_crypto"
```
*Output: Signed initData for Alice (ID 99999).*

**3. Simulating a Referral (Important)**
To test the referral system, use the `--start-param` flag with a valid referral code from an existing user.
```bash
python scripts/generate_telegram_init_data.py --start-param "REF123XYZ"
```
*Output: Signed initData that includes `start_param="REF123XYZ"`. When this user logs in, they will be referred by the owner of that code.*

## Using the Output

Copy the output string and use it in your API requests:

**cURL Example:**
```bash
curl -X POST http://localhost:8000/api/users/auth/telegram/ \
     -H "Content-Type: application/json" \
     -d '{
           "init_data": "<PASTE_OUTPUT_HERE>",
           "start_param": "<OPTIONAL_REPEAT_PARAM>"
         }'
```

## Browser Console Commands

When testing the frontend in development (mock) mode, you can persist the mock authentication using the browser console. This is useful if you want to switch accounts without using URL parameters.

### Set Init Data

Paste your generated init data string (raw, not URL encoded) here:

```javascript
localStorage.setItem('mockTelegramInitData', 'user=%7B%22id%22%3A...');
window.location.reload();
```

### Clear Init Data (Logout)

To clear the stored mock data and simulate a fresh visit:

```javascript
localStorage.removeItem('mockTelegramInitData');
window.location.reload();
```
