from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional
from ..database import get_db
from ..models import Staff
from ..schemas import StaffOut, StaffCreate, StaffUpdate
from ..dependencies import get_current_user, require_super_admin

router = APIRouter()


@router.get("", response_model=List[StaffOut])
def list_staff(
    status: str = "ACTIVE",
    category: Optional[str] = None,
    db: Session = Depends(get_db),
    _=Depends(get_current_user),
):
    q = db.query(Staff)
    if status != "ALL":
        q = q.filter(Staff.status == status)
    if category:
        q = q.filter(Staff.category == category)
    return q.order_by(Staff.full_name).all()


@router.post("", response_model=StaffOut)
def create_staff(
    body: StaffCreate,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    staff = Staff(**body.model_dump())
    db.add(staff)
    db.flush()
    from .audit import log_audit
    log_audit(db, current_user.id, 'CREATE', 'staff', staff.id,
              f"Created staff: {staff.full_name} ({staff.category})")
    db.commit()
    db.refresh(staff)
    return staff


@router.put("/{staff_id}", response_model=StaffOut)
def update_staff(
    staff_id: int,
    body: StaffUpdate,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    staff = db.query(Staff).filter(Staff.id == staff_id).first()
    if not staff:
        raise HTTPException(status_code=404, detail="Staff not found")
    for k, v in body.model_dump(exclude_none=True).items():
        setattr(staff, k, v)
    from .audit import log_audit
    log_audit(db, current_user.id, 'UPDATE', 'staff', staff_id,
              f"Updated staff: {staff.full_name}")
    db.commit()
    db.refresh(staff)
    return staff


@router.delete("/{staff_id}", status_code=204)
def delete_staff(
    staff_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(require_super_admin),
):
    staff = db.query(Staff).filter(Staff.id == staff_id).first()
    if not staff:
        raise HTTPException(status_code=404, detail="Staff not found")
    from .audit import log_audit
    log_audit(db, current_user.id, 'DELETE', 'staff', staff_id,
              f"Deleted staff: {staff.full_name}")
    db.delete(staff)
    db.commit()
