# Simple Loan Calculator — Generated Backend

## Overview

This is a **generated FastAPI backend** for the **Simple Loan Calculator** application. It provides a RESTful API for calculating loan payments and generating detailed amortization schedules for anonymous users.

**Key Features:**
- Calculate monthly loan payments using standard amortization formulas
- Generate complete amortization schedules with payment breakdowns
- Persist loan calculations and schedules to a database
- Retrieve calculation details with eager-loaded amortization entries
- Support for loan amounts from $1 to $100,000,000
- Annual interest rates from 0.01% to 99.99%
- Loan terms from 1 to 600 months (up to 50 years)

**Supported Entities:**
- **LoanCalculation**: Stores input parameters and computed results (monthly payment, total amount paid, total interest paid)
- **AmortizationScheduleEntry**: Represents each payment period with principal/interest breakdown and running balances

## Requirements

- **Python 3.11+**
- **uv** (fast Python package installer and resolver)
- **FastAPI** (web framework)
- **SQLAlchemy** (ORM)
- **Pydantic** (data validation)
- **PostgreSQL** or **SQLite** (database)

## Install uv

Install `uv`, the fast Python package installer:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

After installation, restart your shell or run:

```bash
source $HOME/.cargo/env
```

## Install Dependencies

Once `uv` is installed, install all project dependencies:

```bash
uv sync
```

This reads `pyproject.toml` and installs FastAPI, SQLAlchemy, Uvicorn, and other required packages.

## Run the Backend

Start the FastAPI development server with auto-reload:

```bash
uv run uvicorn main:app --reload
```

The API will be available at **http://localhost:8000**

## API Docs

FastAPI provides interactive API documentation out of the box:

- **Swagger UI**: [http://localhost:8000/docs](http://localhost:8000/docs)
- **ReDoc**: [http://localhost:8000/redoc](http://localhost:8000/redoc)

## OpenAPI JSON

Access the OpenAPI schema in JSON format:

- **OpenAPI Schema**: [http://localhost:8000/openapi.json](http://localhost:8000/openapi.json)

## Project Files

```
.
├── main.py                          # FastAPI app entry point with all routes
├── models.py                        # SQLAlchemy ORM models (LoanCalculation, AmortizationScheduleEntry)
├── schemas.py                       # Pydantic schemas for request/response validation
├── database.py                      # Database connection and session management
├── services.py                      # Business logic for loan calculations and amortization
├── pyproject.toml                   # Project dependencies and metadata
├── README.md                        # This file
└── .env                             # Environment variables (DATABASE_URL, etc.)
```

## Example Workflow

### 1. Create a Loan Calculation with Amortization Schedule

Calculate a $10,000 loan at 5% annual interest for 12 months:

```bash
curl -X POST http://localhost:8000/loan-calculations \
  -H "Content-Type: application/json" \
  -d '{
    "principal_amount": 10000.00,
    "annual_interest_rate": 5.00,
    "loan_term_months": 12
  }'
```

**Response:**
```json
{
  "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "principal_amount": "10000.00",
  "annual_interest_rate": "5.00",
  "loan_term_months": 12,
  "monthly_payment": "856.07",
  "total_amount_paid": "10272.84",
  "total_interest_paid": "272.84",
  "created_at": "2025-01-15T10:30:00Z",
  "updated_at": "2025-01-15T10:30:00Z"
}
```

### 2. Retrieve Loan Calculation Summary

```bash
curl http://localhost:8000/loan-calculations/a1b2c3d4-e5f6-7890-abcd-ef1234567890
```

### 3. Retrieve Full Calculation with Amortization Schedule

Get the complete amortization schedule with all payment details:

```bash
curl http://localhost:8000/loan-calculations/a1b2c3d4-e5f6-7890-abcd-ef1234567890/details
```

**Response includes:**
```json
{
  "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "principal_amount": "10000.00",
  "monthly_payment": "856.07",
  "amortization_schedule_entries": [
    {
      "payment_number": 1,
      "payment_amount": "856.07",
      "principal_portion": "814.40",
      "interest_portion": "41.67",
      "remaining_balance": "9185.60",
      "cumulative_interest": "41.67",
      "cumulative_principal": "814.40"
    },
    {
      "payment_number": 2,
      "payment_amount": "856.07",
      "principal_portion": "817.80",
      "interest_portion": "38.27",
      "remaining_balance": "8367.80",
      "cumulative_interest": "79.94",
      "cumulative_principal": "1632.20"
    }
    // ... remaining 10 payments
  ]
}
```

### 4. List All Calculations

```bash
curl http://localhost:8000/loan-calculations?skip=0&limit=10
```

### 5. Delete a Calculation

```bash
curl -X DELETE http://localhost:8000/loan-calculations/a1b2c3d4-e5f6-7890-abcd-ef1234567890
```

This cascade deletes all associated amortization schedule entries.

## Next Steps

This generated backend is a **working prototype**. To make it production-ready, consider:

1. **Database Persistence**: Configure PostgreSQL connection string in `.env` and run migrations
2. **Authentication & Authorization**: Add user authentication if you want to track calculations per user (currently anonymous)
3. **Code Organization**: Split `main.py` into:
   - `routers/` — API route handlers
   - `services/` — Business logic and calculations
   - `models/` — Database models
   - `schemas/` — Request/response schemas
   - `repositories/` — Data access layer
4. **Tests**: Add unit tests for calculation formulas, integration tests for API endpoints
5. **Validation**: Enhance input validation for edge cases (e.g., extremely large loan amounts)
6. **Error Handling**: Add custom exception handlers and detailed error responses
7. **Logging**: Implement structured logging for debugging and monitoring
8. **CORS**: Configure CORS settings if frontend is hosted on different domain
9. **Rate Limiting**: Add rate limiting to prevent abuse
10. **Export Features**: Implement CSV/PDF export for amortization schedules
11. **Deployment**: Containerize with Docker and deploy to cloud platform

**Formula Reference:**

Monthly Payment: `M = P[r(1+r)^n]/[(1+r)^n-1]`
- P = principal amount
- r = monthly interest rate (annual rate / 12 / 100)
- n = number of payments

Special case: If interest rate is 0%, then `M = P / n`
