# Low-Level Design (LLD) Update - TA-ATS Project

This document provides the updated Low-Level Design details for the TA-ATS project, reflecting the current codebase implementation.

---

## 1. Database Schema

The project uses SQLAlchemy ORM with a SQLite backend (`db.sqlite3`). Below are the primary tables and their relationships.

### 1.1 Table: `users`
| Column | Type | Description |
| :--- | :--- | :--- |
| `id` | Integer | Primary Key, Index |
| `email` | String(254) | Unique, Index, User's email |
| `username` | String(150) | Unique, User's login name |
| `password` | String(128) | Hashed password |
| `role` | String(20) | User role (ADMIN, CANDIDATE, HIRING_MANAGER) |
| `full_name` | String(255) | User's full name |
| `phone` | String(20) | Contact number |
| `location` | String(255) | City/State |
| `skills` | Text | Comma-separated or structured skills |
| `experience_years`| Integer | Years of experience |
| `bio` | Text | Short profile summary |
| `resume` | String(500) | Path to uploaded resume file |
| `mfa_enabled` | Boolean | Whether MFA is active |
| `totp_secret` | String(32) | Secret key for TOTP (MFA) |
| `is_active` | Boolean | Account status |
| `date_joined` | DateTime | Account creation timestamp |

### 1.2 Table: `candidates`
| Column | Type | Description |
| :--- | :--- | :--- |
| `id` | Integer | Primary Key |
| `name` | String(255) | Candidate's name |
| `email` | String(254) | Contact email |
| `phone` | String(20) | Contact phone |
| `experience_years`| Integer | Years of experience |
| `skills` | Text | Extracted skills |
| `applied_role` | String(255) | Role applied for |
| `status` | String(50) | Screening, Interviewing, Hired, etc. |
| `cv_file` | String(500) | Path to CV file |

### 1.3 Table: `job_descriptions`
| Column | Type | Description |
| :--- | :--- | :--- |
| `id` | Integer | Primary Key |
| `title` | String(255) | Job title |
| `location` | String(255) | Job location |
| `work_details` | Text | Full job description |
| `status` | String(50) | Draft, Published, Closed |
| `created_by_id` | Integer | ForeignKey to `users.id` |

### 1.4 Supporting Tables
- **`login_attempts`**: Tracks `failed_attempts` and `is_locked` status for security.
- **`otp_records`**: Stores temporary OTPs and `retry_count`.
- **`auth_event_logs`**: Audit trail for `LOGIN_SUCCESS`, `LOGIN_FAIL`, `LOCKOUT`.
- **`dashboard_widgets`**: Stores widget configuration (title, type, value, order) per user.
- **`job_applications`**: Maps `candidate_id` to `job_description_id` with status tracking.

---

## 2. API Endpoints

The API is built with FastAPI and follows RESTful principles.

### 2.1 Authentication APIs (`/api/v1/auth`)
- `POST /login/`: Validates credentials, checks for lockouts, and returns JWT tokens or MFA requirement.
- `POST /verify-mfa/`: Verifies TOTP code and returns session tokens.
- `POST /token/refresh/`: Issues a new access token using a refresh token.
- `GET /profile/`: Retrieves the current user's profile details.
- `PUT /profile/`: Updates user profile information.
- `POST /profile/resume/upload/`: Handles file upload for resumes.
- `POST /profile/resume/parse/`: Triggers AI-based parsing of the uploaded resume.
- `GET /mfa/setup/`: Generates a TOTP secret and QR code for MFA enrollment.
- `POST /mfa/enable/`: Finalizes MFA activation after verification.

### 2.2 Dashboard & ATS APIs (`/api/v1/dashboard`)
- `GET /`: Returns dashboard statistics and widgets based on user role.
- `POST /chat/`: Interactive chatbot for querying ATS data (e.g., "Show stats").
- `GET /candidates/`: Lists all candidates.
- `POST /candidates/`: Adds a new candidate.
- `GET /job-descriptions/`: Lists JDs created by the user.
- `POST /job-descriptions/`: Creates a new JD.
- `GET /job-applications/`: Lists applications with candidate and JD details.
- `GET /interviews/`: Returns scheduled AI Phone Screen interviews.

---

## 3. Logic & Pseudocode

### 3.1 Login Flow with MFA and Lockout
```python
FUNCTION Login(email, password, ip_address):
    check rate_limit for ip_address
    user = get_user_by_email(email)
    
    if not user: RETURN 401 Unauthorized
    
    attempt = get_login_attempt(user.id)
    if attempt.is_locked:
        if current_time > attempt.locked_at + 30 mins:
            reset_lockout(attempt)
        else:
            RETURN 403 Forbidden ("Account Locked")
            
    if not verify_password(password, user.password):
        increment_failed_attempts(attempt)
        if attempt.failed_attempts >= 5:
            set_locked(attempt)
        RETURN 401 Unauthorized
        
    reset_failed_attempts(attempt)
    
    if user.mfa_enabled:
        RETURN response(mfa_required=True)
    
    access_token = create_jwt(user.id, expires_in=30m)
    refresh_token = create_jwt(user.id, expires_in=7d)
    RETURN response(access_token, refresh_token)
```

### 3.2 Resume Parsing Logic (MCP Service)
```python
FUNCTION ParseResume(file_path):
    text = extract_text_from_file(file_path) # PDF or DOCX
    
    extracted_data = {
        "skills": match_keywords(text, ["Python", "React", "SQL", ...]),
        "experience_years": regex_search(text, r"(\d+) years"),
        "bio_summary": summarize_start_of_text(text)
    }
    
    RETURN extracted_data
```

---

## 4. Missing Components Identified (Add to LLD)

To make the LLD comprehensive, the following architectural details were added based on the implementation:

1.  **Token Management Strategy:** Detailed use of `access` (short-lived) and `refresh` (long-lived) JWT tokens.
2.  **MFA Implementation:** Use of TOTP (Time-based One-Time Password) using `pyotp` and QR code generation for Google Authenticator.
3.  **Audit Logging:** Implementation of `AuthEventLog` to track all security-sensitive operations.
4.  **Static/Media Handling:** Strategy for storing and serving uploaded resumes using FastAPI `StaticFiles`.
5.  **Rate Limiting:** IP-based rate limiting on the login endpoint to prevent brute-force attacks.
6.  **CORS Policy:** Configuration to allow communication between the Next.js frontend and FastAPI backend.
7.  **MCP Architecture:** Use of a separate Model Context Protocol (MCP) service for specialized tasks like OTP generation and Resume parsing, ensuring modularity.

---
