from fastapi import APIRouter, Form, Depends, HTTPException
from fastapi.responses import RedirectResponse
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.security import require_roles
from app.models.models import Customer, Payment

router = APIRouter(dependencies=[Depends(require_roles("admin_cs"))])

@router.post("/customers/{customer_id}/payments")
async def record_payment(customer_id: int, amount: int = Form(...), period: str = Form(...), method: str = Form("cash"), reference: str = Form(None), db: AsyncSession = Depends(get_db)):
    customer = await db.get(Customer, customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    if amount <= 0 or not period.strip():
        raise HTTPException(status_code=422, detail="Nominal dan periode wajib valid")
    db.add(Payment(customer_id=customer_id, amount=amount, period=period.strip(), method=method, reference=reference))
    customer.is_paid = True
    await db.commit()
    return RedirectResponse(url=f"/customers/{customer_id}", status_code=303)
