# Post Management API

This document describes the post management API endpoints for creating, managing, and interacting with posts.

## Features

- **Post Creation**: Create posts with title, description, and media
- **Media Support**: Upload multiple images and videos
- **Engagement**: Like, comment, and share functionality
- **Categories**: Organize posts by categories
- **Tags**: Tag posts for better discoverability
- **Privacy**: Control post visibility
- **Analytics**: Track engagement metrics

## API Endpoints

### Base URL
```
http://localhost:5000/api/posts
```

## 1. Create Post

**POST** `/`

Create a new post with optional media files.

**Headers:**
```
Authorization: Bearer <jwt_token>
Content-Type: multipart/form-data (for media) or application/json
```

**Request Body (Form Data):**
```
title: string (required, max 200 chars)
description: string (required, max 2000 chars)
tags: string (optional, comma-separated)
category: string (optional, enum: general, announcement, event, news, promotion, educational)
visibility: string (optional, enum: public, private, friends_only)
media: file[] (optional, max 10 files, 50MB each)
```

**Response:**
```json
{
  "success": true,
  "message": "Post created successfully",
  "data": {
    "_id": "post_id",
    "title": "Post Title",
    "description": "Post description",
    "author": {
      "_id": "user_id",
      "name": "User Name",
      "email": "user@example.com"
    },
    "media": [
      {
        "type": "image",
        "url": "/uploads/posts/filename.jpg",
        "filename": "filename.jpg",
        "originalName": "original.jpg",
        "size": 1024000,
        "mimeType": "image/jpeg"
      }
    ],
    "likes": [],
    "comments": [],
    "shares": [],
    "tags": ["tag1", "tag2"],
    "category": "general",
    "visibility": "public",
    "isActive": true,
    "isPinned": false,
    "viewCount": 0,
    "engagement": {
      "totalLikes": 0,
      "totalComments": 0,
      "totalShares": 0,
      "totalViews": 0
    },
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:30:00.000Z"
  }
}
```

## 2. Get All Posts

**GET** `/`

Get all posts with pagination and filtering.

**Query Parameters:**
```
page: number (optional, default: 1)
limit: number (optional, default: 10)
category: string (optional)
author: string (optional, user ID)
tags: string (optional, comma-separated)
sortBy: string (optional, default: createdAt)
sortOrder: string (optional, default: desc)
```

**Response:**
```json
{
  "success": true,
  "data": {
    "posts": [...],
    "pagination": {
      "currentPage": 1,
      "totalPages": 5,
      "totalPosts": 50,
      "hasNext": true,
      "hasPrev": false
    }
  }
}
```

## 3. Get Single Post

**GET** `/:id`

Get a single post by ID and increment view count.

**Response:**
```json
{
  "success": true,
  "data": {
    "_id": "post_id",
    "title": "Post Title",
    "description": "Post description",
    "author": {...},
    "media": [...],
    "likes": [...],
    "comments": [...],
    "shares": [...],
    "viewCount": 1,
    "engagement": {...},
    "createdAt": "2025-01-15T10:30:00.000Z",
    "updatedAt": "2025-01-15T10:30:00.000Z"
  }
}
```

## 4. Update Post

**PUT** `/:id`

Update a post (only by the author).

**Headers:**
```
Authorization: Bearer <jwt_token>
Content-Type: application/json
```

**Request Body:**
```json
{
  "title": "Updated Title",
  "description": "Updated description",
  "tags": "new,tags",
  "category": "announcement",
  "visibility": "public"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Post updated successfully",
  "data": {
    "_id": "post_id",
    "title": "Updated Title",
    "description": "Updated description",
    ...
  }
}
```

## 5. Delete Post

**DELETE** `/:id`

Delete a post and its associated media files (only by the author).

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

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

## 6. Like/Unlike Post

**POST** `/:id/like`

Toggle like status for a post.

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

**Response:**
```json
{
  "success": true,
  "message": "Post liked",
  "data": {
    "liked": true,
    "likeCount": 5
  }
}
```

## 7. Add Comment

**POST** `/:id/comment`

Add a comment to a post.

**Headers:**
```
Authorization: Bearer <jwt_token>
Content-Type: application/json
```

**Request Body:**
```json
{
  "content": "This is a comment"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Comment added successfully",
  "data": {
    "_id": "comment_id",
    "user": {
      "_id": "user_id",
      "name": "User Name"
    },
    "content": "This is a comment",
    "likes": [],
    "replies": [],
    "createdAt": "2025-01-15T10:30:00.000Z"
  }
}
```

## 8. Share Post

**POST** `/:id/share`

Share a post to external platforms.

**Headers:**
```
Authorization: Bearer <jwt_token>
Content-Type: application/json
```

**Request Body:**
```json
{
  "platform": "facebook"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Post shared successfully",
  "data": {
    "shareCount": 3
  }
}
```

## 9. Get User Posts

**GET** `/user/:userId`

Get all posts by a specific user.

**Query Parameters:**
```
page: number (optional, default: 1)
limit: number (optional, default: 10)
```

**Response:**
```json
{
  "success": true,
  "data": {
    "posts": [...],
    "pagination": {...}
  }
}
```

## 10. Get Post Statistics

**GET** `/stats`

Get overall post statistics and analytics.

**Response:**
```json
{
  "success": true,
  "data": {
    "overall": {
      "totalPosts": 150,
      "totalLikes": 2500,
      "totalComments": 800,
      "totalShares": 300,
      "totalViews": 10000,
      "avgEngagement": 24.0
    },
    "byCategory": [
      {
        "_id": "general",
        "count": 75
      },
      {
        "_id": "announcement",
        "count": 25
      }
    ]
  }
}
```

## Media Upload

### Supported File Types
- **Images**: JPEG, JPG, PNG, GIF, WebP
- **Videos**: MP4, AVI, MOV, WMV, FLV, WebM

### File Limits
- **Maximum file size**: 50MB per file
- **Maximum files**: 10 files per post
- **Storage location**: `/uploads/posts/`

### File Structure
```
uploads/
└── posts/
    ├── media-1234567890-123456789.jpg
    ├── media-1234567891-123456789.mp4
    └── ...
```

## Error Responses

### 400 Bad Request
```json
{
  "success": false,
  "message": "Validation failed",
  "errors": [
    {
      "field": "title",
      "message": "Title must be between 1 and 200 characters"
    }
  ]
}
```

### 401 Unauthorized
```json
{
  "success": false,
  "message": "Access token is required"
}
```

### 403 Forbidden
```json
{
  "success": false,
  "message": "You can only update your own posts"
}
```

### 404 Not Found
```json
{
  "success": false,
  "message": "Post not found"
}
```

### 413 Payload Too Large
```json
{
  "success": false,
  "message": "File too large. Maximum size is 50MB."
}
```

## Database Schema

### Post Model
```javascript
{
  title: String (required, max 200 chars),
  description: String (required, max 2000 chars),
  author: ObjectId (ref: User),
  media: [{
    type: String (enum: image, video),
    url: String,
    filename: String,
    originalName: String,
    size: Number,
    mimeType: String,
    thumbnail: String (for videos)
  }],
  likes: [{
    user: ObjectId (ref: User),
    likedAt: Date
  }],
  comments: [{
    user: ObjectId (ref: User),
    content: String (max 500 chars),
    likes: [ObjectId (ref: User)],
    replies: [{
      user: ObjectId (ref: User),
      content: String (max 300 chars),
      createdAt: Date
    }]
  }],
  shares: [{
    user: ObjectId (ref: User),
    sharedAt: Date,
    platform: String (enum: facebook, twitter, linkedin, whatsapp, copy_link)
  }],
  tags: [String],
  category: String (enum: general, announcement, event, news, promotion, educational),
  visibility: String (enum: public, private, friends_only),
  isActive: Boolean,
  isPinned: Boolean,
  viewCount: Number,
  engagement: {
    totalLikes: Number,
    totalComments: Number,
    totalShares: Number,
    totalViews: Number
  },
  createdAt: Date,
  updatedAt: Date
}
```

## Testing

Run the post API tests:
```bash
npm run test:posts
```

## Setup Instructions

1. **Install dependencies** (if not already installed):
   ```bash
   npm install multer
   ```

2. **Create uploads directory**:
   ```bash
   mkdir -p uploads/posts
   ```

3. **Start the server**:
   ```bash
   npm run dev
   ```

4. **Test the API**:
   ```bash
   npm run test:posts
   ```

## Security Features

- **Authentication**: JWT token required for protected operations
- **Authorization**: Users can only modify their own posts
- **File Validation**: Strict file type and size validation
- **Input Sanitization**: All inputs are validated and sanitized
- **Rate Limiting**: Applied to prevent abuse
- **File Storage**: Secure file storage with unique filenames
