# Domestic Violence Report API Documentation

## Overview

The Domestic Violence Report API provides a comprehensive system for managing domestic violence incident reports with document upload capabilities. The system supports creating, updating, retrieving, and deleting reports, with built-in logic to prevent duplicate reports by updating the existing report for the same user.

## Features

- **Smart Create/Update Logic**: Automatically updates existing reports for the same user
- **Document Upload Support**: Upload multiple supporting documents (images, PDFs, etc.)
- **Comprehensive Validation**: Input validation for all report fields
- **File Type Security**: Restricted file types and size limits for security
- **Pagination Support**: Efficient data retrieval with pagination
- **Admin Access**: Special endpoints for administrative oversight
- **Unified Response Format**: Consistent API responses using UniResponse utility

## API Endpoints

### Base URL

```
/v1/domestic-violence-reports
```

### Authentication

All endpoints require authentication via JWT Bearer token:

```
Authorization: Bearer <jwt_token>
```

## Endpoints

### 1. Create or Update Report

**POST** `/v1/domestic-violence-reports`

Creates a new domestic violence report or updates an existing one if a report already exists for the same user on the same date.

#### Request Body (multipart/form-data)

| Field           | Type          | Required | Description                                                  |
| --------------- | ------------- | -------- | ------------------------------------------------------------ |
| `incidentDate`  | string (date) | Yes      | Date when the incident occurred (YYYY-MM-DD)                 |
| `incidentTime`  | string        | Yes      | Time when the incident occurred (HH:MM)                      |
| `location`      | string        | Yes      | Location where the incident occurred                         |
| `description`   | string        | Yes      | Detailed description of the incident                         |
| `witnesses`     | string        | No       | Information about any witnesses                              |
| `policeReport`  | boolean       | No       | Whether a police report was filed (default: false)           |
| `violenceTypes` | array         | Yes      | Types of violence reported (e.g., ["physical", "emotional"]) |
| `notes`         | string        | No       | Additional notes about the report                            |
| `documents`     | file[]        | No       | Supporting documents (max 10 files, 5MB each)                |

#### Supported File Types

- Images: JPEG, PNG, GIF
- Documents: PDF, DOC, DOCX
- Text: TXT

#### Response

**201 Created** (New Report)

```json
{
  "success": true,
  "message": "Domestic violence report created successfully with documents",
  "data": {
    "id": "report_123",
    "incidentDate": "2024-01-15T00:00:00.000Z",
    "incidentTime": "14:30",
    "location": "123 Main Street, City, State",
    "description": "Physical altercation occurred...",
    "witnesses": "Neighbor John Smith witnessed the incident",
    "policeReport": true,
    "violenceTypes": ["physical", "emotional", "verbal"],
    "notes": "Case worker notes...",
    "userId": "user_123",
    "user": {
      "id": "user_123",
      "email": "user@example.com",
      "full_name": "John Doe"
    },
    "documents": [
      {
        "id": "doc_123",
        "name": "incident_photo.jpg",
        "fileName": "1640995200000-abc123.jpg",
        "filePath": "uploads/domestic-violence-reports/1640995200000-abc123.jpg",
        "fileSize": 1024000,
        "mimeType": "image/jpeg",
        "uploadedAt": "2024-01-01T00:00:00.000Z"
      }
    ],
    "createdAt": "2024-01-01T00:00:00.000Z",
    "updatedAt": "2024-01-01T00:00:00.000Z"
  }
}
```

**200 OK** (Updated Report)

```json
{
  "success": true,
  "message": "Domestic violence report updated successfully with documents",
  "data": {
    // Same structure as above
  }
}
```

### 2. Get All Reports by User

**GET** `/v1/domestic-violence-reports`

Retrieves all domestic violence reports for the authenticated user with pagination.

#### Query Parameters

| Parameter | Type   | Required | Default | Description                          |
| --------- | ------ | -------- | ------- | ------------------------------------ |
| `page`    | number | No       | 1       | Page number for pagination           |
| `limit`   | number | No       | 10      | Number of reports per page (max 100) |

#### Response

```json
{
  "success": true,
  "message": "Reports retrieved successfully",
  "data": {
    "reports": [
      {
        "id": "report_123",
        "incidentDate": "2024-01-15T00:00:00.000Z",
        "incidentTime": "14:30",
        "location": "123 Main Street, City, State",
        "description": "Physical altercation occurred...",
        "witnesses": "Neighbor John Smith witnessed the incident",
        "policeReport": true,
        "violenceTypes": ["physical", "emotional", "verbal"],
        "notes": "Case worker notes...",
        "userId": "user_123",
        "user": {
          "id": "user_123",
          "email": "user@example.com",
          "full_name": "John Doe"
        },
        "documents": [],
        "createdAt": "2024-01-01T00:00:00.000Z",
        "updatedAt": "2024-01-01T00:00:00.000Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 25,
      "totalPages": 3
    }
  }
}
```

### 3. Get Report by ID

**GET** `/v1/domestic-violence-reports/{reportId}`

Retrieves a specific domestic violence report by ID.

#### Path Parameters

| Parameter  | Type   | Required | Description                     |
| ---------- | ------ | -------- | ------------------------------- |
| `reportId` | string | Yes      | Unique identifier of the report |

#### Response

```json
{
  "success": true,
  "message": "Report retrieved successfully",
  "data": {
    // Same structure as individual report in create/update response
  }
}
```

### 4. Update Report

**PUT** `/v1/domestic-violence-reports/{reportId}`

Updates an existing domestic violence report.

#### Path Parameters

| Parameter  | Type   | Required | Description                     |
| ---------- | ------ | -------- | ------------------------------- |
| `reportId` | string | Yes      | Unique identifier of the report |

#### Request Body (application/json)

| Field           | Type          | Required | Description                          |
| --------------- | ------------- | -------- | ------------------------------------ |
| `incidentDate`  | string (date) | No       | Date when the incident occurred      |
| `incidentTime`  | string        | No       | Time when the incident occurred      |
| `location`      | string        | No       | Location where the incident occurred |
| `description`   | string        | No       | Detailed description of the incident |
| `witnesses`     | string        | No       | Information about any witnesses      |
| `policeReport`  | boolean       | No       | Whether a police report was filed    |
| `violenceTypes` | array         | No       | Types of violence reported           |
| `notes`         | string        | No       | Additional notes about the report    |

#### Response

```json
{
  "success": true,
  "message": "Report updated successfully",
  "data": {
    // Updated report data
  }
}
```

### 5. Delete Report

**DELETE** `/v1/domestic-violence-reports/{reportId}`

Deletes a domestic violence report and all associated documents.

#### Path Parameters

| Parameter  | Type   | Required | Description                     |
| ---------- | ------ | -------- | ------------------------------- |
| `reportId` | string | Yes      | Unique identifier of the report |

#### Response

```json
{
  "success": true,
  "message": "Report deleted successfully",
  "data": {
    "message": "Report deleted successfully"
  }
}
```

### 6. Get Documents for Report

**GET** `/v1/domestic-violence-reports/{reportId}/documents`

Retrieves all documents associated with a specific report.

#### Path Parameters

| Parameter  | Type   | Required | Description                     |
| ---------- | ------ | -------- | ------------------------------- |
| `reportId` | string | Yes      | Unique identifier of the report |

#### Response

```json
{
  "success": true,
  "message": "Documents retrieved successfully",
  "data": [
    {
      "id": "doc_123",
      "name": "incident_photo.jpg",
      "fileName": "1640995200000-abc123.jpg",
      "filePath": "uploads/domestic-violence-reports/1640995200000-abc123.jpg",
      "fileSize": 1024000,
      "mimeType": "image/jpeg",
      "uploadedAt": "2024-01-01T00:00:00.000Z"
    }
  ]
}
```

### 7. Delete Document

**DELETE** `/v1/domestic-violence-reports/documents/{documentId}`

Deletes a specific document from a report.

#### Path Parameters

| Parameter    | Type   | Required | Description                       |
| ------------ | ------ | -------- | --------------------------------- |
| `documentId` | string | Yes      | Unique identifier of the document |

#### Response

```json
{
  "success": true,
  "message": "Document deleted successfully",
  "data": {
    "message": "Document deleted successfully"
  }
}
```

### 8. Get All Reports (Admin)

**GET** `/v1/domestic-violence-reports/admin/all`

Retrieves all domestic violence reports across all users (Admin only).

#### Query Parameters

| Parameter | Type   | Required | Default | Description                          |
| --------- | ------ | -------- | ------- | ------------------------------------ |
| `page`    | number | No       | 1       | Page number for pagination           |
| `limit`   | number | No       | 10      | Number of reports per page (max 100) |

#### Response

```json
{
  "success": true,
  "message": "All reports retrieved successfully",
  "data": {
    "reports": [
      // Array of all reports with user information
    ],
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 150,
      "totalPages": 15
    }
  }
}
```

## Error Responses

### 400 Bad Request

```json
{
  "success": false,
  "message": "Validation error message",
  "errors": {
    "field": "Error details"
  }
}
```

### 401 Unauthorized

```json
{
  "success": false,
  "message": "Unauthorized"
}
```

### 404 Not Found

```json
{
  "success": false,
  "message": "Report not found or access denied"
}
```

### 413 Payload Too Large

```json
{
  "success": false,
  "message": "File too large. Maximum size is 5MB"
}
```

### 500 Internal Server Error

```json
{
  "success": false,
  "message": "Failed to create domestic violence report"
}
```

## Usage Examples

### Create Report with Documents

```bash
curl -X POST http://localhost:3000/v1/domestic-violence-reports \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -F "incidentDate=2024-01-15" \
  -F "incidentTime=14:30" \
  -F "location=123 Main Street, City, State" \
  -F "description=Physical altercation occurred..." \
  -F "violenceTypes=[\"physical\",\"emotional\"]" \
  -F "policeReport=true" \
  -F "documents=@photo1.jpg" \
  -F "documents=@document.pdf"
```

### Update Report

```bash
curl -X PUT http://localhost:3000/v1/domestic-violence-reports/report_123 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "description": "Updated incident description",
    "policeReport": true,
    "violenceTypes": ["physical", "emotional", "verbal"]
  }'
```

### Get User Reports with Pagination

```bash
curl -X GET "http://localhost:3000/v1/domestic-violence-reports?page=1&limit=5" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

### Delete Report

```bash
curl -X DELETE http://localhost:3000/v1/domestic-violence-reports/report_123 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

## Smart Create/Update Logic

The API implements intelligent create/update logic:

1. **User Check**: When creating a report, the system checks if any report already exists for the same user
2. **Automatic Update**: If a report exists, it updates the latest report instead of creating a new one
3. **Document Preservation**: Existing documents are preserved when updating
4. **Clear Feedback**: Different status codes (201 vs 200) and messages indicate create vs update operations

### Example Flow

```javascript
// First submission
POST /v1/domestic-violence-reports
{
  "incidentDate": "2024-01-15",
  "description": "First incident report"
}
// Response: 201 Created

// Second submission (any date)
POST /v1/domestic-violence-reports
{
  "incidentDate": "2024-01-20",
  "description": "Updated incident details"
}
// Response: 200 OK (updated existing report)
```

## File Upload Security

- **File Type Validation**: Only allows specific file types (JPEG, PNG, GIF, PDF, DOC, DOCX, TXT)
- **Size Limits**: Maximum 5MB per file, maximum 10 files per request
- **Secure Storage**: Files are stored in a dedicated directory with unique filenames
- **Automatic Cleanup**: Files are automatically deleted when reports are deleted

## Database Schema

The API uses the following Prisma models:

- **DomesticViolenceReport**: Main report entity
- **Document**: File attachments linked to reports
- **users**: User information (linked via foreign key)

## Implementation Details

### Architecture

- **Controller Layer**: `DomesticViolenceReportController` - Handles HTTP requests and responses
- **Service Layer**: `DomesticViolenceReportService` - Business logic and validation
- **Repository Layer**: `DomesticViolenceReportRepository` - Database operations
- **Middleware**: Multer for file uploads, authentication middleware

### Key Features

- **Async Handlers**: All endpoints use `asyncHandler` for proper error handling
- **Unified Responses**: Consistent API responses using `UniResponse` utility
- **Input Validation**: Comprehensive validation for all inputs
- **Error Handling**: Graceful error handling with appropriate HTTP status codes
- **File Management**: Secure file upload and storage with automatic cleanup

## Dependencies

- **Express.js**: Web framework
- **Prisma**: Database ORM
- **Multer**: File upload middleware
- **JWT**: Authentication
- **PostgreSQL**: Database
- **TypeScript**: Type safety

## Getting Started

1. Install dependencies: `npm install`
2. Set up your `.env` file with required variables
3. Run database migrations: `npx prisma migrate dev`
4. Start development server: `npm run dev`
5. Access Swagger documentation: `http://localhost:3000/api-docs`

## Notes

- All timestamps are in UTC format
- File uploads are processed asynchronously
- The system prevents duplicate reports for the same user on the same date
- Admin endpoints require proper role-based access control (to be implemented)
- File paths are relative to the project root
- Maximum file size is 5MB per file
- Maximum 10 files can be uploaded per request
