from fastapi import APIRouter, Depends, Query, status, HTTPException
from sqlalchemy.orm import Session
from typing import Optional
from utils.utils import get_db
from . import handler
from .schema import (
    CalculationCreate,
    CalculationResponse,
    CalculationDetailResponse,
    PaginatedCalculationResponse,
)

router = APIRouter(prefix="/calculations", tags=["Loan Calculations"])


@router.post(
    "/",
    response_model=CalculationResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Create Loan Calculation",
    description="Creates a new loan calculation with input parameters (principal, annual interest rate, loan term). Automatically calculates monthly payment, total interest, and generates complete amortization schedule. Returns 400 if validation fails.",
)
def create_calculation_route(data: CalculationCreate, db: Session = Depends(get_db)):
    return handler.create_calculation(db, data)


@router.get(
    "/{calculation_id}",
    response_model=CalculationResponse,
    summary="Get Calculation Summary",
    description="Retrieves a single loan calculation summary by ID without amortization schedule entries. Returns 404 if calculation does not exist.",
)
def get_calculation_route(calculation_id: str, db: Session = Depends(get_db)):
    return handler.get_calculation(db, calculation_id)


@router.get(
    "/{calculation_id}/details",
    response_model=CalculationDetailResponse,
    summary="Get Calculation With Schedule",
    description="Retrieves a loan calculation with full amortization schedule including all payment entries. Each entry shows payment number, date, balances, principal/interest breakdown, and cumulative interest. Returns 404 if calculation does not exist.",
)
def get_calculation_details_route(calculation_id: str, db: Session = Depends(get_db)):
    return handler.get_calculation_details(db, calculation_id)


@router.get(
    "/",
    response_model=PaginatedCalculationResponse,
    summary="List Calculations",
    description="Returns a paginated list of all loan calculations ordered by creation date (newest first). Supports standard pagination via limit and offset parameters.",
)
def list_calculations_route(
    limit: int = Query(20, ge=1, le=100),
    offset: int = Query(0, ge=0),
    db: Session = Depends(get_db),
):
    return handler.list_calculations(db, limit, offset)


@router.delete(
    "/{calculation_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="Delete Calculation",
    description="Deletes a loan calculation and cascades deletion to all associated amortization schedule entries. Returns 404 if calculation does not exist.",
)
def delete_calculation_route(calculation_id: str, db: Session = Depends(get_db)):
    handler.delete_calculation(db, calculation_id)