# Treelogy API Documentation

## Survey Data Collection APIs

### 1. Submit Survey Data
**Endpoint:** `POST /api/surveys/submit`

**Description:** Submit tree survey data from mobile app

**Request Body:**
```json
{
  "tree_name": "Banyan Tree",
  "local_name": "Bargad",
  "other_name": "Ficus benghalensis",
  "latitude": 19.0760,
  "longitude": 72.8777,
  "tree_height": 25.5,
  "tree_girth": 8.2,
  "tree_age": 45,
  "tree_condition": "HEALTHY",
  "tree_ownership": "PUBLIC",
  "economic_importance": "HIGH",
  "remarks": "Large heritage tree with extensive canopy",
  "species_type": "BANYAN",
  "is_heritage": true,
  "is_rare": false,
  "is_indigenous": true,
  "is_exotic": false,
  "host_plants": "Epiphytic ferns, orchids",
  "images": ["tree1.jpg", "tree1_canopy.jpg"],
  "user_id": 1,
  "client_id": 1,
  "treelogy_id": 1,
  "survey_date": "2024-01-15T10:30:00Z"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Survey submitted successfully",
  "data": {
    "survey_id": 1,
    "tree_name": "Banyan Tree",
    // ... other survey fields
  }
}
```

### 2. Get Project Surveys
**Endpoint:** `GET /api/surveys/project/:treelogy_id`

**Description:** Get surveys for a specific project (requires authentication)

**Query Parameters:**
- `page` (optional): Page number (default: 1)
- `limit` (optional): Items per page (default: 100)
- `verified_only` (optional): Filter verified surveys only (true/false)
- `species_type` (optional): Filter by species type
- `tree_condition` (optional): Filter by tree condition
- `start_date` (optional): Filter surveys from date
- `end_date` (optional): Filter surveys to date

**Response:**
```json
{
  "success": true,
  "message": "Surveys retrieved successfully",
  "data": {
    "surveys": [...],
    "total": 50,
    "page": 1,
    "limit": 100,
    "totalPages": 1
  }
}
```

### 3. Get Survey Statistics
**Endpoint:** `GET /api/surveys/project/:treelogy_id/statistics`

**Description:** Get survey statistics for dashboard (requires authentication)

**Response:**
```json
{
  "success": true,
  "message": "Statistics retrieved successfully",
  "data": {
    "totalTrees": 150,
    "verifiedTrees": 120,
    "speciesCount": 25,
    "heritageTrees": 5,
    "rareTrees": 3,
    "indigenousTrees": 100,
    "exoticTrees": 50,
    "conditionDistribution": [...],
    "ownershipDistribution": [...],
    "topSpecies": [...]
  }
}
```

## Map Data APIs

### 1. Get Map Data
**Endpoint:** `GET /api/map/project/:treelogy_id/data`

**Description:** Get survey data formatted for map display (requires authentication)

**Query Parameters:**
- `verified_only` (optional): Show only verified surveys
- `species_type` (optional): Filter by species type
- `tree_condition` (optional): Filter by tree condition
- `is_heritage` (optional): Filter heritage trees
- `is_rare` (optional): Filter rare species
- `is_indigenous` (optional): Filter indigenous trees
- `is_exotic` (optional): Filter exotic trees

**Response:**
```json
{
  "success": true,
  "message": "Map data retrieved successfully",
  "data": {
    "project": {
      "id": 1,
      "name": "GreenHeights Tower A",
      "landmark": "Bandra Kurla Complex"
    },
    "surveys": [
      {
        "id": 1,
        "name": "Banyan Tree",
        "localName": "Bargad",
        "otherName": "Ficus benghalensis",
        "position": {
          "lat": 19.0760,
          "lng": 72.8777
        },
        "details": {
          "height": 25.5,
          "girth": 8.2,
          "age": 45,
          "condition": "HEALTHY",
          "ownership": "PUBLIC",
          "economicImportance": "HIGH",
          "remarks": "Large heritage tree",
          "speciesType": "BANYAN",
          "isHeritage": true,
          "isRare": false,
          "isIndigenous": true,
          "isExotic": false,
          "hostPlants": "Epiphytic ferns",
          "images": ["tree1.jpg"],
          "surveyDate": "2024-01-15T10:30:00Z",
          "verified": true,
          "verifiedAt": "2024-01-16T09:00:00Z"
        }
      }
    ],
    "total": 1
  }
}
```

### 2. Get Dashboard Statistics
**Endpoint:** `GET /api/map/project/:treelogy_id/stats`

**Description:** Get dashboard statistics (requires authentication)

**Response:**
```json
{
  "success": true,
  "message": "Dashboard statistics retrieved successfully",
  "data": {
    "totalTrees": 150,
    "verifiedTrees": 120,
    "speciesCount": 25,
    "heritageTrees": 5,
    "rareTrees": 3,
    "indigenousTrees": 100,
    "exoticTrees": 50,
    "mostDominantSpecies": "BANYAN",
    "avgHeight": "15.5",
    "avgGirth": "45.2",
    "avgAge": "25.3"
  }
}
```

### 3. Get Chart Data
**Endpoint:** `GET /api/map/project/:treelogy_id/charts`

**Description:** Get chart data for dashboard (requires authentication)

**Query Parameters:**
- `chart_type`: Type of chart (condition, ownership, species, economic_importance)

**Response:**
```json
{
  "success": true,
  "message": "Chart data retrieved successfully",
  "data": {
    "chartType": "condition",
    "data": [
      {
        "tree_condition": "HEALTHY",
        "count": "120"
      },
      {
        "tree_condition": "AVERAGE",
        "count": "25"
      }
    ]
  }
}
```

## Dashboard APIs

### Dashboard Cards
**GET** `/api/surveys/project/{treelogy_id}/dashboard/cards`

Retrieves main dashboard cards data (Total Trees Surveyed, Total Verified, Species Count).

### Dashboard Charts
- **Condition Chart:** `GET /api/surveys/project/{treelogy_id}/dashboard/charts/condition`
- **Remarks Chart:** `GET /api/surveys/project/{treelogy_id}/dashboard/charts/remarks`
- **Ownership Chart:** `GET /api/surveys/project/{treelogy_id}/dashboard/charts/ownership`
- **Species Chart:** `GET /api/surveys/project/{treelogy_id}/dashboard/charts/species`
- **Economic Importance Chart:** `GET /api/surveys/project/{treelogy_id}/dashboard/charts/economic-importance`

For detailed documentation of dashboard endpoints, see [DASHBOARD_API_DOCUMENTATION.md](./DASHBOARD_API_DOCUMENTATION.md).

## Database Management

### Project Database Creation
When a new project (treelogy) is created, the system automatically:
1. Creates a new PostgreSQL database with the project's `dbname`
2. Creates the `surveys` table with all required fields
3. Sets up appropriate indexes for performance
4. Establishes connection pooling for the project database

### Survey Data Model
The survey table includes the following fields:
- `survey_id` (Primary Key)
- `tree_name`, `local_name`, `other_name`
- `latitude`, `longitude` (for map positioning)
- `tree_height`, `tree_girth`, `tree_age`
- `tree_condition`, `tree_ownership`, `economic_importance`
- `remarks`, `species_type`
- `is_heritage`, `is_rare`, `is_indigenous`, `is_exotic`
- `host_plants`, `images` (JSON array)
- `user_id`, `client_id`, `treelogy_id`
- `survey_date`, `entered_time`
- `status`, `verified`, `verified_by`, `verified_at`

## Authentication

Most endpoints require authentication via JWT token in the Authorization header:
```
Authorization: Bearer <jwt_token>
```

The `/api/surveys/submit` endpoint is public and doesn't require authentication for mobile app submissions.

## Error Handling

All endpoints return consistent error responses:
```json
{
  "success": false,
  "message": "Error message",
  "data": "Additional error details"
}
```

Common HTTP status codes:
- 200: Success
- 201: Created
- 400: Bad Request
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 500: Internal Server Error
