from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from core.database import get_core_db
from .models import AphisCatalog
from .dto import AphisCatalogDTO

router = APIRouter(prefix="/aphis-catalog", tags=["APHIS Catalog"])


@router.get("/", response_model=List[AphisCatalogDTO])
def list_aphis_catalog(company_id: int, db: Session = Depends(get_core_db)):
    records = (
        db.query(AphisCatalog)
        .filter(AphisCatalog.company_id == company_id)
        .order_by(AphisCatalog.id)
        .all()
    )
    return records


@router.post("/", response_model=AphisCatalogDTO)
def create_aphis_catalog(data: AphisCatalogDTO, company_id: int, db: Session = Depends(get_core_db)):
    payload = data.model_dump(exclude={"id"})
    record = AphisCatalog(**payload, company_id=company_id)
    db.add(record)
    db.commit()
    db.refresh(record)
    return record


@router.put("/{record_id}", response_model=AphisCatalogDTO)
def update_aphis_catalog(
    record_id: int, data: AphisCatalogDTO, company_id: int, db: Session = Depends(get_core_db)
):
    record = (
        db.query(AphisCatalog)
        .filter(AphisCatalog.id == record_id, AphisCatalog.company_id == company_id)
        .first()
    )
    if not record:
        raise HTTPException(status_code=404, detail="Registro no encontrado")

    for field, value in data.model_dump(exclude={"id"}).items():
        setattr(record, field, value)

    db.commit()
    db.refresh(record)
    return record


@router.delete("/{record_id}", status_code=204)
def delete_aphis_catalog(record_id: int, company_id: int, db: Session = Depends(get_core_db)):
    record = (
        db.query(AphisCatalog)
        .filter(AphisCatalog.id == record_id, AphisCatalog.company_id == company_id)
        .first()
    )
    if not record:
        raise HTTPException(status_code=404, detail="Registro no encontrado")
    db.delete(record)
    db.commit()
