# Personal Details API Documentation

This document describes the Personal Details API endpoints for managing user profile information.

## 📋 Overview

The Personal Details API allows users to store and manage their personal profile information including basic details, location information, and professional details.

## 🔗 Base URL
```
/api/personal-details
```

## 🔐 Authentication
All endpoints require JWT authentication. Include the token in the Authorization header:
```
Authorization: Bearer <your_jwt_token>
```

## 📊 Data Model

### PersonalDetails Schema
```javascript
{
  userId: ObjectId,           // Reference to User
  fullName: String,          // Required, 2-100 chars, letters only
  gender: String,            // Required, enum: ['Male', 'Female', 'Other']
  emailId: String,           // Required, valid email format
  bloodGroup: String,        // Required, enum: ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']
  pincodeNative: String,     // Required, 6-digit pincode
  state: String,             // Required, auto-filled from pincode
  district: String,          // Required, auto-filled from pincode
  nativePlace: String,       // Required, city/town name
  occupation: String,        // Required, enum: ['School Student', 'College Student', 'Employee', 'Business', 'Professionals + Business', 'Others']
  nameMeaning: String,       // Optional, max 500 chars
  isCompleted: Boolean,      // Auto-calculated completion status
  lastUpdated: Date,         // Auto-updated timestamp
  createdAt: Date,           // Auto-generated
  updatedAt: Date            // Auto-generated
}
```

## 🛠️ API Endpoints

### 1. Create/Update Personal Details
**POST** `/api/personal-details`

Creates new personal details or updates existing ones.

**Request Body:**
```json
{
  "fullName": "John Doe",
  "gender": "Male",
  "emailId": "john.doe@example.com",
  "bloodGroup": "O+",
  "pincodeNative": "110001",
  "state": "Delhi",
  "district": "Central Delhi",
  "nativePlace": "New Delhi",
  "occupation": "Employee",
  "nameMeaning": "John means God is gracious"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Personal details saved successfully",
  "data": {
    "personalDetails": {
      "_id": "68c5130bb96b7888d08865af",
      "userId": "68c5130bb96b7888d08865ab",
      "fullName": "John Doe",
      "gender": "Male",
      "emailId": "john.doe@example.com",
      "bloodGroup": "O+",
      "pincodeNative": "110001",
      "state": "Delhi",
      "district": "Central Delhi",
      "nativePlace": "New Delhi",
      "occupation": "Employee",
      "nameMeaning": "John means God is gracious",
      "isCompleted": true,
      "lastUpdated": "2025-01-13T12:00:00.000Z",
      "createdAt": "2025-01-13T12:00:00.000Z",
      "updatedAt": "2025-01-13T12:00:00.000Z"
    },
    "completionPercentage": 100,
    "isCompleted": true
  }
}
```

### 2. Get Personal Details
**GET** `/api/personal-details`

Retrieves the authenticated user's personal details.

**Response:**
```json
{
  "success": true,
  "message": "Personal details retrieved successfully",
  "data": {
    "personalDetails": { /* PersonalDetails object */ },
    "completionPercentage": 100,
    "isCompleted": true
  }
}
```

### 3. Get Personal Details by User ID
**GET** `/api/personal-details/:userId`

Retrieves personal details for a specific user (only own data allowed).

**Response:** Same as above

### 4. Update Personal Details (Partial)
**PUT** `/api/personal-details`

Updates specific fields of personal details.

**Request Body:**
```json
{
  "occupation": "Business",
  "nameMeaning": "Updated name meaning"
}
```

**Response:** Same as create/update

### 5. Get Profile Completion Status
**GET** `/api/personal-details/completion`

Gets the completion percentage and missing fields.

**Response:**
```json
{
  "success": true,
  "message": "Profile completion status retrieved",
  "data": {
    "completionPercentage": 80,
    "isCompleted": false,
    "missingFields": ["bloodGroup", "nativePlace"],
    "lastUpdated": "2025-01-13T12:00:00.000Z"
  }
}
```

### 6. Delete Personal Details
**DELETE** `/api/personal-details`

Deletes the user's personal details.

**Response:**
```json
{
  "success": true,
  "message": "Personal details deleted successfully"
}
```

### 7. Get All Personal Details (Admin)
**GET** `/api/personal-details/admin/all`

Retrieves all personal details (for testing/admin purposes).

**Response:**
```json
{
  "success": true,
  "message": "All personal details retrieved successfully",
  "data": {
    "personalDetails": [ /* Array of PersonalDetails objects */ ],
    "total": 10
  }
}
```

## 🔍 Field Validations

### Required Fields
- `fullName`: 2-100 characters, letters and spaces only
- `gender`: Must be 'Male', 'Female', or 'Other'
- `emailId`: Valid email format
- `bloodGroup`: Must be one of the valid blood types
- `pincodeNative`: 6-digit pincode (1-9 followed by 5 digits)
- `state`: 2-50 characters
- `district`: 2-50 characters
- `nativePlace`: 2-100 characters
- `occupation`: Must be one of the predefined options

### Optional Fields
- `nameMeaning`: Maximum 500 characters

## 🚫 Error Responses

### Validation Error (400)
```json
{
  "success": false,
  "message": "Validation failed",
  "errors": [
    {
      "msg": "Full name must be between 2 and 100 characters",
      "param": "fullName",
      "location": "body"
    }
  ]
}
```

### Authentication Error (401)
```json
{
  "success": false,
  "message": "Access token required"
}
```

### Not Found Error (404)
```json
{
  "success": false,
  "message": "Personal details not found",
  "data": null
}
```

### Server Error (500)
```json
{
  "success": false,
  "message": "Failed to save personal details",
  "error": "Error message details"
}
```

## 🧪 Testing

### Test Script
Run the personal details test script:
```bash
npm run test:personal-details
```

### Manual Testing with cURL

#### 1. Create Personal Details
```bash
curl -X POST http://localhost:5000/api/personal-details \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "fullName": "John Doe",
    "gender": "Male",
    "emailId": "john.doe@example.com",
    "bloodGroup": "O+",
    "pincodeNative": "110001",
    "state": "Delhi",
    "district": "Central Delhi",
    "nativePlace": "New Delhi",
    "occupation": "Employee"
  }'
```

#### 2. Get Personal Details
```bash
curl -X GET http://localhost:5000/api/personal-details \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

#### 3. Get Profile Completion
```bash
curl -X GET http://localhost:5000/api/personal-details/completion \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

## 🔒 Security Features

- **Authentication Required**: All endpoints require valid JWT token
- **Input Validation**: Comprehensive validation for all fields
- **Request Sanitization**: XSS and NoSQL injection prevention
- **Rate Limiting**: Protection against abuse
- **Ownership Verification**: Users can only access their own data
- **Request Size Limiting**: 1MB limit per request

## 📈 Completion Tracking

The API automatically tracks profile completion:
- **Completion Percentage**: Calculated based on filled fields
- **Missing Fields**: List of required fields not yet filled
- **Auto-update**: Completion status updates automatically

## 🗄️ Database Indexes

For optimal performance, the following indexes are created:
- `userId`: Primary lookup index
- `pincodeNative`: For location-based queries
- `state, district`: For regional queries

## 🔄 Auto-updates

- `lastUpdated`: Updated on every save operation
- `isCompleted`: Recalculated on every save operation
- `completionPercentage`: Recalculated on every save operation
