# INDI-VOUCH Backend API Documentation

## Base URL
```
http://localhost:3000
```

## Authentication
The API uses JWT (JSON Web Tokens) for authentication. Include the token in the Authorization header:
```
Authorization: Bearer <your_jwt_token>
```

---

## User Authentication APIs

### 1. User Login
**Endpoint:** `POST /api/user/auth/login`

**Description:** Authenticate user and receive JWT token. Users with any status (active/inactive) can login.

**Request Body:**
```json
{
  "username": "john_doe",     // Optional (at least one identifier required)
  "email": "john@example.com", // Optional (at least one identifier required)
  "mobile": "9876543210",     // Optional (at least one identifier required)
  "password": "your_password" // Required (minimum 6 characters)
}
```

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Login successful",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": 1,
      "name": "John Doe",
      "username": "john_doe",
      "email": "john@example.com",
      "mobile": "9876543210",
      "status": 1
    }
  }
}
```

**Response (Error - 401):**
```json
{
  "success": false,
  "message": "Invalid credentials"
}
```

---

### 2. User Registration
**Endpoint:** `POST /api/user/auth/register`

**Description:** Register a new user

**Request Body:**
```json
{
  "name": "John Doe",
  "username": "john_doe",
  "email": "john@example.com",
  "mobile": "9876543210",
  "password": "secure_password123" // Required (minimum 6 characters)
}
```

**Response (Success - 201):**
```json
{
  "success": true,
  "message": "User registered successfully",
  "data": {
    "userId": 1,
    "username": "john_doe",
    "email": "john@example.com"
  }
}
```

**Response (Error - 400):**
```json
{
  "success": false,
  "message": "Password must be at least 6 characters long"
}
```

**Response (Error - 409):**
```json
{
  "success": false,
  "message": "User already exists with this username, email, or mobile"
}
```

---

## User Profile APIs

### 3. Get User Profile
**Endpoint:** `GET /api/user/profile`

**Description:** Get current user's profile information

**Headers:**
```
Authorization: Bearer <jwt_token>
```

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Profile retrieved successfully",
  "data": {
    "id": 1,
    "name": "John Doe",
    "username": "john_doe",
    "email": "john@example.com",
    "mobile": "9876543210",
    "status": 1,
    "created_at": "2023-11-01T12:00:00.000Z",
    "updated_at": "2023-11-01T12:00:00.000Z"
  }
}
```

---

### 4. Update User Profile
**Endpoint:** `PUT /api/user/profile`

**Description:** Update current user's profile information

**Headers:**
```
Authorization: Bearer <jwt_token>
```

**Request Body:**
```json
{
  "name": "John Smith",      // Optional
  "email": "johnsmith@example.com", // Optional
  "mobile": "9876543211"     // Optional
}
```

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Profile updated successfully",
  "data": {
    "id": 1,
    "name": "John Smith",
    "username": "john_doe",
    "email": "johnsmith@example.com",
    "mobile": "9876543211",
    "status": 1,
    "updated_at": "2023-11-01T13:00:00.000Z"
  }
}
```

---

## Admin Authentication APIs

### 5. Admin Login (Not Implemented)
**Endpoint:** `POST /api/admin/auth/login`

**Description:** Admin authentication (placeholder)

**Response (501):**
```json
{
  "success": false,
  "message": "Admin authentication not implemented yet"
}
```

---

## System APIs

### 6. Health Check
**Endpoint:** `GET /health`

**Response:**
```json
{
  "status": "OK",
  "uptime": 123.456,
  "timestamp": "2023-11-01T12:00:00.000Z"
}
```

### 7. Database Health Check
**Endpoint:** `GET /db-health`

**Response:**
```json
{
  "status": "OK",
  "database": "Connected",
  "timestamp": "2023-11-01T12:00:00.000Z"
}
```

### 8. Get Database Tables
**Endpoint:** `GET /api/tables`

**Response:**
```json
{
  "success": true,
  "tables": [
    {"Tables_in_indi-vouch-new": "user"},
    {"Tables_in_indi-vouch-new": "payment"},
    {"Tables_in_indi-vouch-new": "binary_tree"}
  ],
  "count": 3
}
```

---

## Error Responses

### Common Error Codes:
- **400**: Bad Request - Invalid input data
- **401**: Unauthorized - Invalid or missing authentication
- **403**: Forbidden - Insufficient privileges
- **404**: Not Found - Resource not found
- **409**: Conflict - Resource already exists
- **500**: Internal Server Error - Server error
- **501**: Not Implemented - Feature not implemented

### Error Response Format:
```json
{
  "success": false,
  "message": "Error description",
  "error": "Detailed error message (in development mode)"
}
```

---

## Notes

1. **Password Security**: 
   - Passwords are hashed using bcrypt with 10 salt rounds before storing in database
   - Minimum password length is 6 characters
   - Passwords are never returned in API responses

2. **User Status**: User status values:
   - `0`: Inactive (can still login and access APIs)
   - `1`: Active (can login and access APIs)
   - Other values may indicate different states (can still login and access APIs)
   - Note: All users regardless of status can login and access protected endpoints

3. **JWT Token**: Tokens expire in 24 hours by default. Configure `JWT_EXPIRES_IN` in environment variables.

4. **Database**: Ensure the `indi-vouch-new` database is created and the SQL schema is imported before using the APIs.

5. **User Table**: The user table now includes a `password` field (varchar(150)) for storing hashed passwords.

6. **Settings Table**: The settings table stores application configuration values with key-value pairs.

7. **Payment Table**: The payment table stores all payment transactions including commissions.

8. **Database Tables**: The complete database includes: user, user_status, generation, binary_tree, payment, settings.

---

## Debug & Development APIs

### 1. Check All Database Tables
**Endpoint:** `GET /api/debug/all-tables`

**Description:** Get list of all tables in the database

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "All database tables",
  "tables": [
    {"Tables_in_indi-vouch-new": "user"},
    {"Tables_in_indi-vouch-new": "user_status"},
    {"Tables_in_indi-vouch-new": "generation"},
    {"Tables_in_indi-vouch-new": "binary_tree"},
    {"Tables_in_indi-vouch-new": "payment"},
    {"Tables_in_indi-vouch-new": "settings"}
  ],
  "count": 6
}
```

### 2. Check Table Structure
**Endpoint:** `GET /api/debug/table/:tableName`

**Description:** Get structure of a specific table

**Example:** `GET /api/debug/table/settings`

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Structure of table: settings",
  "structure": [
    {
      "Field": "id",
      "Type": "int(11)",
      "Null": "NO",
      "Key": "PRI",
      "Default": null,
      "Extra": "auto_increment"
    },
    {
      "Field": "key_name",
      "Type": "varchar(255)",
      "Null": "NO",
      "Key": "UNI",
      "Default": null,
      "Extra": ""
    }
  ],
  "table_name": "settings"
}
```

---

## Settings Management APIs

### 1. Get Flag Value by Name
**Endpoint:** `GET /api/settings/flag/:flagName`

**Description:** Get a specific flag value from settings table by flag name

**Example:** `GET /api/settings/flag/referal_reward_on_joining`

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Flag value retrieved successfully",
  "data": {
    "flag_name": "referal_reward_on_joining",
    "flag_value": "100.00"
  }
}
```

**Response (Not Found - 404):**
```json
{
  "success": false,
  "message": "Flag 'invalid_flag' not found in settings"
}
```

### 2. Get Multiple Flag Values
**Endpoint:** `POST /api/settings/flags`

**Description:** Get multiple flag values at once

**Request Body:**
```json
{
  "flag_names": [
    "referal_reward_on_joining",
    "app_name",
    "commission_status"
  ]
}
```

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Flag values retrieved successfully",
  "data": {
    "flag_values": {
      "referal_reward_on_joining": "100.00",
      "app_name": "INDI-VOUCH",
      "commission_status": "active"
    },
    "requested_flags": ["referal_reward_on_joining", "app_name", "commission_status"],
    "found_count": 3
  }
}
```

### 3. Get All Settings
**Endpoint:** `GET /api/settings`

**Description:** Retrieve all application settings (public access)

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Settings retrieved successfully",
  "data": {
    "settings": {
      "app_name": {
        "value": "INDI-VOUCH",
        "description": "Application name",
        "type": "string",
        "updated_at": "2023-11-01T12:00:00.000Z"
      },
      "max_users_per_sponsor": {
        "value": "100",
        "description": "Maximum users per sponsor",
        "type": "number",
        "updated_at": "2023-11-01T12:00:00.000Z"
      }
    },
    "raw_settings": [...],
    "count": 2
  }
}
```

### 2. Get Specific Setting
**Endpoint:** `GET /api/settings/:key`

**Description:** Retrieve a specific setting by key

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Setting retrieved successfully",
  "data": {
    "key": "app_name",
    "value": "INDI-VOUCH",
    "description": "Application name",
    "type": "string",
    "created_at": "2023-11-01T10:00:00.000Z",
    "updated_at": "2023-11-01T12:00:00.000Z"
  }
}
```

**Response (Error - 404):**
```json
{
  "success": false,
  "message": "Setting with key 'invalid_key' not found"
}
```

### 3. Update Setting (Admin Only)
**Endpoint:** `PUT /api/settings/:key`

**Description:** Update an existing setting value (requires admin authentication)

**Headers:**
```
Authorization: Bearer <admin_jwt_token>
```

**Request Body:**
```json
{
  "value": "New Value",
  "description": "Updated description (optional)"
}
```

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Setting updated successfully",
  "data": {
    "key": "app_name",
    "value": "New Value",
    "description": "Updated description",
    "type": "string",
    "updated_at": "2023-11-01T13:00:00.000Z"
  }
}
```

### 4. Create New Setting (Admin Only)
**Endpoint:** `POST /api/settings`

**Description:** Create a new setting (requires admin authentication)

**Headers:**
```
Authorization: Bearer <admin_jwt_token>
```

**Request Body:**
```json
{
  "key_name": "new_setting",
  "value": "setting_value",
  "description": "Setting description (optional)",
  "type": "string"
}
```

**Response (Success - 201):**
```json
{
  "success": true,
  "message": "Setting created successfully",
  "data": {
    "id": 123,
    "key": "new_setting",
    "value": "setting_value",
    "description": "Setting description",
    "type": "string"
  }
}
```

### 5. Delete Setting (Admin Only)
**Endpoint:** `DELETE /api/settings/:key`

**Description:** Delete an existing setting (requires admin authentication)

**Headers:**
```
Authorization: Bearer <admin_jwt_token>
```

**Response (Success - 200):**
```json
{
  "success": true,
  "message": "Setting deleted successfully",
  "data": {
    "deleted_key": "setting_key"
  }
}
```

---

## Environment Variables Required

```env
PORT=3000
DB_HOST=localhost
DB_PORT=3306
DB_NAME=indi-vouch-new
DB_USER=root
DB_PASSWORD=
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
JWT_EXPIRES_IN=24h
```
