# Profile API Documentation

## Overview
The Profile API allows authenticated users to manage their own account information, including personal details, profile images, and passwords. All endpoints require JWT authentication except for the public user profile endpoint.

**Base URL:** `/profile`

**Authentication:** Bearer token in Authorization header (except public endpoints)

---

## Table of Contents
1. [Get Own Profile](#1-get-own-profile)
2. [Update Profile](#2-update-profile)
3. [Update Profile Image](#3-update-profile-image)
4. [Change Password](#4-change-password)
5. [Delete Account](#5-delete-account)
6. [Get Public User Profile](#6-get-public-user-profile)

---

## 1. Get Own Profile

Get the authenticated user's full private profile information.

**Endpoint:** `GET /profile`

**Authentication:** Required (JWT)

**Rate Limit:** 100 requests per hour

### Request

```bash
curl -X GET http://localhost:5000/profile \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Profile retrieved successfully",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "first_name": "John",
    "last_name": "Doe",
    "username": "johndoe",
    "email": "john.doe@example.com",
    "phone_number": "+1234567890",
    "date_of_birth": "1990-05-15",
    "address": "123 Main St",
    "city": "New York",
    "country": "USA",
    "profile_image": "/static/uploads/profiles/a1b2c3d4-e5f6-7890-abcd-ef1234567890.jpg",
    "role": "customer",
    "is_email_verified": true,
    "is_verified": false,
    "created_at": "2024-01-15T10:30:00",
    "updated_at": "2024-01-20T14:45:00"
  }
}
```

### Error Responses

**401 Unauthorized** - Missing or invalid token
```json
{
  "success": false,
  "message": "Invalid or expired token",
  "data": null
}
```

**404 Not Found** - User not found
```json
{
  "success": false,
  "message": "User not found",
  "data": null
}
```

---

## 2. Update Profile

Update the authenticated user's profile information. Only specified fields will be updated.

**Endpoint:** `PUT /profile`

**Authentication:** Required (JWT)

**Rate Limit:** 50 requests per hour

### Allowed Fields
- `first_name` (string, 2-50 characters)
- `last_name` (string, 2-50 characters)
- `phone_number` (string, optional, must be unique)
- `date_of_birth` (string, ISO format: YYYY-MM-DD)
- `address` (string, optional)
- `city` (string, optional)
- `country` (string, optional)

**Note:** Email, username, and role cannot be updated via this endpoint.

### Request

```bash
curl -X PUT http://localhost:5000/profile \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "John",
    "last_name": "Smith",
    "phone_number": "+1987654321",
    "date_of_birth": "1990-05-15",
    "address": "456 Oak Avenue",
    "city": "Los Angeles",
    "country": "USA"
  }'
```

### Minimal Update Example

```bash
curl -X PUT http://localhost:5000/profile \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "city": "San Francisco"
  }'
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Profile updated successfully",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "first_name": "John",
    "last_name": "Smith",
    "username": "johndoe",
    "email": "john.doe@example.com",
    "phone_number": "+1987654321",
    "date_of_birth": "1990-05-15",
    "address": "456 Oak Avenue",
    "city": "Los Angeles",
    "country": "USA",
    "profile_image": "/static/uploads/profiles/a1b2c3d4-e5f6-7890-abcd-ef1234567890.jpg",
    "role": "customer",
    "is_email_verified": true,
    "is_verified": false,
    "created_at": "2024-01-15T10:30:00",
    "updated_at": "2024-01-21T09:15:00"
  }
}
```

### Error Responses

**400 Bad Request** - No data provided
```json
{
  "success": false,
  "message": "No data provided",
  "data": null
}
```

**400 Bad Request** - No valid fields
```json
{
  "success": false,
  "message": "No valid fields provided for update",
  "data": null
}
```

**400 Bad Request** - Validation error
```json
{
  "success": false,
  "message": "First name must be between 2 and 50 characters",
  "data": null
}
```

**400 Bad Request** - Phone number already in use
```json
{
  "success": false,
  "message": "Phone number already in use",
  "data": null
}
```

**401 Unauthorized** - Invalid token
```json
{
  "success": false,
  "message": "Invalid or expired token",
  "data": null
}
```

---

## 3. Update Profile Image

Upload or update the authenticated user's profile image.

**Endpoint:** `PUT /profile/image`

**Authentication:** Required (JWT)

**Rate Limit:** 20 requests per hour

**Content-Type:** `multipart/form-data`

**Allowed Extensions:** jpg, jpeg, png, webp

**File Naming:** Images are stored as `{user_id}.{extension}` in `/static/uploads/profiles/`

### Request

```bash
curl -X PUT http://localhost:5000/profile/image \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -F "image=@/path/to/profile-photo.jpg"
```

### JavaScript Example (Frontend)

```javascript
const formData = new FormData();
formData.append('image', fileInput.files[0]);

fetch('http://localhost:5000/profile/image', {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${token}`
  },
  body: formData
})
.then(response => response.json())
.then(data => console.log(data));
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Profile image updated successfully",
  "data": {
    "profile_image": "/static/uploads/profiles/a1b2c3d4-e5f6-7890-abcd-ef1234567890.jpg"
  }
}
```

### Error Responses

**400 Bad Request** - No file provided
```json
{
  "success": false,
  "message": "No image file provided",
  "data": null
}
```

**400 Bad Request** - Empty filename
```json
{
  "success": false,
  "message": "No image file selected",
  "data": null
}
```

**400 Bad Request** - Invalid file type
```json
{
  "success": false,
  "message": "File type not allowed. Allowed types: jpg, jpeg, png, webp",
  "data": null
}
```

**401 Unauthorized** - Invalid token
```json
{
  "success": false,
  "message": "Invalid or expired token",
  "data": null
}
```

---

## 4. Change Password

Change the authenticated user's password. Requires current password for verification.

**Endpoint:** `PUT /profile/password`

**Authentication:** Required (JWT)

**Rate Limit:** 10 requests per hour

**Security Notes:**
- Current password must be provided for verification
- New password must meet strength requirements (min 8 chars, uppercase, lowercase, number, special char)
- New password cannot be the same as current password

### Request

```bash
curl -X PUT http://localhost:5000/profile/password \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "current_password": "OldPassword123!",
    "new_password": "NewSecurePass456!"
  }'
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Password changed successfully",
  "data": null
}
```

### Error Responses

**400 Bad Request** - Missing fields
```json
{
  "success": false,
  "message": "Missing required fields: current_password, new_password",
  "data": null
}
```

**400 Bad Request** - Incorrect current password
```json
{
  "success": false,
  "message": "Current password is incorrect",
  "data": null
}
```

**400 Bad Request** - Weak password
```json
{
  "success": false,
  "message": "Password must be at least 8 characters and include uppercase, lowercase, number, and special character",
  "data": null
}
```

**400 Bad Request** - Same password
```json
{
  "success": false,
  "message": "New password must be different from current password",
  "data": null
}
```

**401 Unauthorized** - Invalid token
```json
{
  "success": false,
  "message": "Invalid or expired token",
  "data": null
}
```

---

## 5. Delete Account

Soft delete (deactivate) the authenticated user's account. This sets `is_active=False`. The account can be reactivated by an administrator.

**Endpoint:** `DELETE /profile`

**Authentication:** Required (JWT)

**Rate Limit:** 5 requests per hour

**Important:** This is a soft delete. User data is retained but the account is deactivated.

### Request

```bash
curl -X DELETE http://localhost:5000/profile \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Account deactivated successfully",
  "data": null
}
```

### Error Responses

**400 Bad Request** - Account already deactivated
```json
{
  "success": false,
  "message": "Account is already deactivated",
  "data": null
}
```

**401 Unauthorized** - Invalid token
```json
{
  "success": false,
  "message": "Invalid or expired token",
  "data": null
}
```

---

## 6. Get Public User Profile

Get public profile information for any user by their ID. This endpoint is used to display owner information on property listings.

**Endpoint:** `GET /profile/users/{user_id}/public`

**Authentication:** Not required

**Rate Limit:** 100 requests per hour

**Returns:** Limited public information only (no email, phone, or sensitive data)

### Request

```bash
curl -X GET http://localhost:5000/profile/users/a1b2c3d4-e5f6-7890-abcd-ef1234567890/public \
  -H "Content-Type: application/json"
```

### Success Response (200 OK)

```json
{
  "success": true,
  "message": "User profile retrieved successfully",
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "username": "johndoe",
    "first_name": "John",
    "profile_image": "/static/uploads/profiles/a1b2c3d4-e5f6-7890-abcd-ef1234567890.jpg",
    "role": "owner",
    "is_verified": true
  }
}
```

### Error Responses

**404 Not Found** - User not found
```json
{
  "success": false,
  "message": "User not found",
  "data": null
}
```

---

## Common Error Codes

| Status Code | Description |
|-------------|-------------|
| 200 | Success |
| 400 | Bad Request - Invalid input or validation error |
| 401 | Unauthorized - Missing or invalid JWT token |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - Resource doesn't exist |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error |

---

## Rate Limiting

All endpoints have rate limits. When exceeded, you'll receive:

```json
{
  "success": false,
  "message": "Rate limit exceeded. Try again later.",
  "data": null
}
```

Response headers include rate limit information:
- `X-RateLimit-Limit`: Maximum requests allowed
- `X-RateLimit-Remaining`: Requests remaining
- `X-RateLimit-Reset`: Time when limit resets

---

## Authentication Flow

1. **Register/Login** → Receive JWT tokens (access_token, refresh_token)
2. **Store Tokens** → Save in secure storage (e.g., httpOnly cookies or secure localStorage)
3. **Include Token** → Add to Authorization header: `Bearer YOUR_ACCESS_TOKEN`
4. **Handle Expiry** → Use refresh token to get new access token when it expires

### Example Header

```
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

---

## Best Practices

### For Frontend Developers

1. **Token Management**
   - Store tokens securely
   - Include Authorization header in all authenticated requests
   - Handle 401 errors by refreshing token or redirecting to login

2. **Error Handling**
   - Always check `success` field in response
   - Display `message` field to users for error feedback
   - Handle rate limiting gracefully with retry logic

3. **Form Validation**
   - Validate inputs client-side before sending to API
   - Match server-side validation rules
   - Provide clear error messages to users

4. **File Uploads**
   - Use FormData for profile image uploads
   - Validate file type and size before upload
   - Show upload progress to users

5. **Optimistic Updates**
   - Update UI immediately for better UX
   - Revert on error
   - Show loading states during requests

### Example: Update Profile with Error Handling

```javascript
async function updateProfile(profileData, token) {
  try {
    const response = await fetch('http://localhost:5000/profile', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(profileData)
    });

    const data = await response.json();

    if (!data.success) {
      // Handle error
      console.error(data.message);
      return { success: false, error: data.message };
    }

    // Success
    return { success: true, profile: data.data };

  } catch (error) {
    console.error('Network error:', error);
    return { success: false, error: 'Network error occurred' };
  }
}
```

---

## Testing Endpoints

### Setup
1. Register a new user or login to get JWT token
2. Copy the `access_token` from login response
3. Replace `YOUR_JWT_TOKEN` in curl examples with your actual token

### Quick Test Sequence

```bash
# 1. Get profile
curl -X GET http://localhost:5000/profile \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

# 2. Update profile
curl -X PUT http://localhost:5000/profile \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"city": "Test City"}'

# 3. Get public profile (replace user_id)
curl -X GET http://localhost:5000/profile/users/USER_ID/public
```

---

## Support

For questions or issues:
- Backend Team: backend@affixwebadverts.com
- API Issues: Create ticket in project management system
- Documentation Updates: Submit PR to API docs repository