# /routers/invoices.py
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from typing import List
from ....db import database
from ...models.saas.invoices import (
    SaaSInvoiceCreate, SaaSInvoiceDB, SaaSInvoiceUpdate
)
from ...services.saas.invoices import (
    create_invoice_service,
    list_invoices_service,
    get_invoice_service,
    update_invoice_status_service,
    run_due_reminders
)
from ...dependencies.auth import get_current_userdetails

router = APIRouter(prefix="/invoices", tags=["Invoices"])

@router.post("/", response_model=SaaSInvoiceDB)
async def create_invoice(
    payload: SaaSInvoiceCreate,
    background_tasks: BackgroundTasks,
    db=Depends(database.get_mongo_db),
    user=Depends(get_current_userdetails)
):
    try:
        return await create_invoice_service(payload, db, background_tasks)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/", response_model=List[SaaSInvoiceDB])
async def list_invoices(
    db=Depends(database.get_mongo_db),
    user=Depends(get_current_userdetails)
):
    # global vs per-account logic can be added here
    return await list_invoices_service(db, account_id=user.account_id)

@router.get("/{invoice_id}", response_model=SaaSInvoiceDB)
async def get_invoice(
    invoice_id: str,
    db=Depends(database.get_mongo_db),
    user=Depends(get_current_userdetails)
):
    try:
        return await get_invoice_service(invoice_id, db)
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))

@router.patch("/{invoice_id}/status", response_model=SaaSInvoiceDB)
async def update_status(
    invoice_id: str,
    payload: SaaSInvoiceUpdate,
    background_tasks: BackgroundTasks,
    db=Depends(database.get_mongo_db),
    user=Depends(get_current_userdetails)
):
    try:
        return await update_invoice_status_service(invoice_id, payload, db, background_tasks)
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))

@router.post("/reminders")
async def trigger_reminders(
    background_tasks: BackgroundTasks,
    db=Depends(database.get_mongo_db)
):
    await run_due_reminders(db, background_tasks)
    return {"status": "reminders scheduled"}
