# Followers API Documentation

## Overview
This API provides comprehensive follower management functionality including suggested followers, follow/unfollow operations, and mutual friends discovery. The system matches users based on interests, school codes, college codes, native places, and location data.

## Models

### Follower Model
```javascript
{
  followerId: ObjectId,     // User who is following
  followingId: ObjectId,    // User being followed
  status: String,           // 'requested', 'accepted', 'rejected'
  requestedAt: Date,        // When request was made
  respondedAt: Date,        // When request was accepted/rejected
  message: String,          // Optional message with request
  createdAt: Date,          // Auto-generated
  updatedAt: Date           // Auto-generated
}
```

## API Endpoints

### 1. Get Suggested Followers
**GET** `/api/followers/suggested/:userId`

Get suggested followers for a user based on matching criteria.

#### Parameters
- `userId` (path): The user ID to get suggestions for
- No limit restriction - returns all available suggestions

#### Authentication
Requires valid JWT token in Authorization header.

#### Matching Criteria
Users are matched based on:
- **Interests** (highest weight: 10 points per common interest)
- **School Code** (high weight: 15 points)
- **College Code** (high weight: 15 points)
- **Native Place** (medium weight: 8 points)
- **Same Pincode + State** (medium weight: 12 points)
- **Same State** (low weight: 5 points)

#### Fallback Suggestions
The API always provides comprehensive suggestions including:
- **Matched Users**: Users with high compatibility scores based on interests, school, college, location
- **Opposite Gender Users**: Users of the opposite gender (if user's gender is specified)
- **Same Gender Users**: Users of the same gender
- **All Remaining Users**: Any other verified users not already included
- **Bidirectional Exclusion**: Excludes users who are already following each other in either direction
- **Randomized Order**: Additional suggestions are shuffled for variety
- **No Limits**: Returns all available suggestions without any count restrictions

#### Response
```javascript
{
  "success": true,
  "data": [
    {
      "_id": "user_id",
      "name": "User Name",
      "profileImage": "image_url",
      "about": "User bio",
      "interests": ["interest1", "interest2"],
      "schoolDetails": { "schoolCode": "code", "schoolName": "name" },
      "collegeDetails": { "collegeCode": "code", "collegeName": "name" },
      "nativePlace": "place",
      "state": "state",
      "pincodeNative": "pincode",
      "gender": "Male",
      "matchScore": 25,
      "matchReasons": ["3 common interests: tech, music, sports", "Same college: XYZ University"],
      "mutualFriendsCount": 5,
      "mutualFriends": [
        {
          "_id": "friend_id",
          "name": "Friend Name",
          "profileImage": "image_url"
        }
      ]
    }
  ],
  "total": 20
}
```

### 2. Send Follow Request
**POST** `/api/followers/follow`

Send a follow request to another user.

#### Request Body
```javascript
{
  "followingId": "user_id_to_follow",
  "message": "Optional message with request"
}
```

#### Response
```javascript
{
  "success": true,
  "message": "Follow request sent successfully",
  "data": {
    "_id": "follow_id",
    "followerId": "requester_id",
    "followingId": {
      "_id": "target_user_id",
      "name": "Target User",
      "profileImage": "image_url"
    },
    "status": "requested",
    "message": "Optional message",
    "requestedAt": "2024-01-01T00:00:00.000Z"
  }
}
```

### 3. Accept/Reject Follow Request
**PUT** `/api/followers/:followId/status`

Accept or reject a follow request.

#### Parameters
- `followId` (path): The follow request ID

#### Request Body
```javascript
{
  "status": "accepted" // or "rejected"
}
```

#### Response
```javascript
{
  "success": true,
  "message": "Follow request accepted successfully",
  "data": {
    "_id": "follow_id",
    "followerId": {
      "_id": "follower_id",
      "name": "Follower Name",
      "profileImage": "image_url"
    },
    "followingId": "user_id",
    "status": "accepted",
    "requestedAt": "2024-01-01T00:00:00.000Z",
    "respondedAt": "2024-01-01T01:00:00.000Z"
  }
}
```

### 4. Unfollow User
**DELETE** `/api/followers/:followId`

Unfollow a user or cancel a follow request.

#### Parameters
- `followId` (path): The follow relationship ID

#### Response
```javascript
{
  "success": true,
  "message": "Unfollowed successfully"
}
```

### 5. Get User's Followers
**GET** `/api/followers/:userId/followers`

Get list of users who follow the specified user.

#### Parameters
- `userId` (path): The user ID
- `status` (query, optional): Filter by status ('accepted', 'requested', 'rejected') - default: 'accepted'

#### Response
```javascript
{
  "success": true,
  "data": [
    {
      "_id": "follow_id",
      "followerId": {
        "_id": "follower_id",
        "name": "Follower Name",
        "profileImage": "image_url",
        "about": "Bio",
        "interests": ["interest1", "interest2"]
      },
      "status": "accepted",
      "requestedAt": "2024-01-01T00:00:00.000Z"
    }
  ],
  "total": 15
}
```

### 6. Get Users Following
**GET** `/api/followers/:userId/following`

Get list of users that the specified user is following.

#### Parameters
- `userId` (path): The user ID
- `status` (query, optional): Filter by status ('accepted', 'requested', 'rejected') - default: 'accepted'

#### Response
```javascript
{
  "success": true,
  "data": [
    {
      "_id": "follow_id",
      "followingId": {
        "_id": "following_id",
        "name": "Following Name",
        "profileImage": "image_url",
        "about": "Bio",
        "interests": ["interest1", "interest2"]
      },
      "status": "accepted",
      "requestedAt": "2024-01-01T00:00:00.000Z"
    }
  ],
  "total": 25
}
```

### 7. Get Follow Requests
**GET** `/api/followers/:userId/requests`

Get pending follow requests for a user (only accessible by the user themselves).

#### Parameters
- `userId` (path): The user ID (must match authenticated user)

#### Response
```javascript
{
  "success": true,
  "data": [
    {
      "_id": "follow_id",
      "followerId": {
        "_id": "requester_id",
        "name": "Requester Name",
        "profileImage": "image_url",
        "about": "Bio",
        "interests": ["interest1", "interest2"]
      },
      "status": "requested",
      "message": "Optional message",
      "requestedAt": "2024-01-01T00:00:00.000Z"
    }
  ],
  "total": 3
}
```

### 8. Check Follow Status
**GET** `/api/followers/:userId1/:userId2/status`

Check the follow status between two users.

#### Parameters
- `userId1` (path): First user ID (follower)
- `userId2` (path): Second user ID (following)

#### Response
```javascript
{
  "success": true,
  "data": {
    "followerId": "user_id_1",
    "followingId": "user_id_2",
    "status": "accepted" // or "requested", "rejected", or null if no relationship
  }
}
```

### 9. Get Mutual Friends
**GET** `/api/followers/:userId1/:userId2/mutual`

Get mutual friends between two users.

#### Parameters
- `userId1` (path): First user ID
- `userId2` (path): Second user ID

#### Response
```javascript
{
  "success": true,
  "data": [
    {
      "_id": "mutual_friend_id",
      "name": "Mutual Friend Name",
      "profileImage": "image_url",
      "about": "Bio",
      "interests": ["interest1", "interest2"]
    }
  ],
  "total": 8
}
```

## Error Responses

All endpoints return consistent error responses:

```javascript
{
  "success": false,
  "message": "Error description",
  "error": "Detailed error message (in development)"
}
```

### Common Error Codes
- `400`: Bad Request (invalid data, self-follow attempt, etc.)
- `401`: Unauthorized (missing or invalid token)
- `403`: Forbidden (trying to access others' requests)
- `404`: Not Found (user, follow relationship not found)
- `500`: Internal Server Error

## Usage Examples

### JavaScript/Fetch
```javascript
// Get suggested followers (no limit - returns all available)
const response = await fetch('/api/followers/suggested/user123', {
  headers: {
    'Authorization': 'Bearer your_jwt_token',
    'Content-Type': 'application/json'
  }
});
const suggestions = await response.json();

// Send follow request
const followResponse = await fetch('/api/followers/follow', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer your_jwt_token',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    followingId: 'user456',
    message: 'Hey! I think we have similar interests.'
  })
});

// Accept follow request
const acceptResponse = await fetch('/api/followers/follow123/status', {
  method: 'PUT',
  headers: {
    'Authorization': 'Bearer your_jwt_token',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    status: 'accepted'
  })
});
```

### cURL Examples
```bash
# Get suggested followers (no limit - returns all available)
curl -H "Authorization: Bearer your_jwt_token" \
     "http://localhost:5500/api/followers/suggested/user123"

# Send follow request
curl -X POST \
     -H "Authorization: Bearer your_jwt_token" \
     -H "Content-Type: application/json" \
     -d '{"followingId":"user456","message":"Hello!"}' \
     "http://localhost:5500/api/followers/follow"

# Accept follow request
curl -X PUT \
     -H "Authorization: Bearer your_jwt_token" \
     -H "Content-Type: application/json" \
     -d '{"status":"accepted"}' \
     "http://localhost:5500/api/followers/follow123/status"
```

## Features

### Smart Matching Algorithm
- **Interest-based matching**: Users with common interests get higher scores
- **Educational matching**: Same school/college connections are prioritized
- **Location-based matching**: Users from same native place or state
- **Mutual friends**: Shows mutual connections to build trust

### Privacy & Security
- All endpoints require authentication
- Users can only view their own follow requests
- Prevents self-following
- Validates all input data

### Performance Optimizations
- Indexed database queries for fast lookups
- Efficient mutual friends calculation
- Pagination support for large datasets
- Cached user profile data in responses

## Database Indexes

The Follower model includes the following indexes for optimal performance:
- Compound index on `followerId` and `followingId` (unique)
- Index on `followerId` and `status`
- Index on `followingId` and `status`

## Integration Notes

1. **Authentication**: All endpoints require valid JWT tokens
2. **User Verification**: Only verified users are suggested to others
3. **Rate Limiting**: Consider implementing rate limiting for follow requests
4. **Notifications**: Integrate with notification system for follow requests
5. **Privacy Settings**: Consider adding privacy controls for follower visibility

## Future Enhancements

- Block/unblock functionality
- Follow suggestions based on activity patterns
- Bulk follow operations
- Advanced filtering options
- Follow request expiration
- Analytics for follower growth
