# /routers/invoices.py
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from typing import List,Optional
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 app.v1.dependencies.auth import get_current_userdetails

router = APIRouter()

@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("/")
async def list_invoices(
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    status: Optional[str] = None,
    created_date_from: Optional[str] = None,
    created_date_to: Optional[str] = None,
    db=Depends(database.get_mongo_db),
    user=Depends(get_current_userdetails),
    current_user = Depends(get_current_userdetails)
):
    # global vs per-account logic can be added here
    account_id = current_user.get("account_id")  # 🔹 extract account_id
    return await list_invoices_service( skip, limit, q, status, created_date_from, created_date_to, db, 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)
):  
    print("Coming invoice id view page 5050")
    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"}
