from fastapi import APIRouter, Request, Form, Depends, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.core.database import get_db
from app.core.security import require_roles
from app.models.models import Customer
import os

router = APIRouter(dependencies=[Depends(require_roles("admin_cs"))])
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))

@router.get("/customers/{customer_id}/edit", response_class=HTMLResponse)
async def edit_customer_page(customer_id: int, request: Request, db: AsyncSession = Depends(get_db)):
    customer = await db.get(Customer, customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    return templates.TemplateResponse(request=request, name="edit_customer.html", context={"customer": customer})

@router.post("/customers/{customer_id}/edit")
async def edit_customer(customer_id: int, name: str = Form(...), address: str = Form(...), phone: str = Form(...), harga_paket: int = Form(...), jatuh_tempo: 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")
    customer.name = name.strip()
    customer.address = address.strip()
    customer.phone = phone.strip()
    customer.harga_paket = max(0, harga_paket)
    if jatuh_tempo:
        from datetime import datetime, timezone
        customer.jatuh_tempo = datetime.fromisoformat(jatuh_tempo).replace(tzinfo=timezone.utc)
    await db.commit()
    return RedirectResponse(url=f"/customers/{customer_id}", status_code=303)

@router.post("/customers/{customer_id}/archive")
async def archive_customer(customer_id: int, db: AsyncSession = Depends(get_db)):
    customer = await db.get(Customer, customer_id)
    if not customer:
        raise HTTPException(status_code=404, detail="Pelanggan tidak ditemukan")
    customer.is_archived = not customer.is_archived
    await db.commit()
    return RedirectResponse(url="/customers", status_code=303)
