from datetime import datetime, timezone

from fastapi import HTTPException, status
from sqlalchemy.orm import Session

from .dto import SupplierCreate, SupplierUpdate
from .models import Supplier


def get_suppliers(
    db: Session,
    tenant_id: int,
    company_id: int,
    search: str | None = None,
    supplier_status: str | None = None,
) -> list[Supplier]:
    query = db.query(Supplier).filter(
        Supplier.tenant_id == tenant_id,
        Supplier.company_id == company_id,
        Supplier.deleted_at.is_(None),
    )
    if search:
        pattern = f"%{search}%"
        query = query.filter(
            Supplier.name.ilike(pattern)
            | Supplier.trade_name.ilike(pattern)
            | Supplier.rfc.ilike(pattern)
        )
    if supplier_status:
        query = query.filter(Supplier.status == supplier_status)
    return query.order_by(Supplier.name.asc()).all()


def get_supplier(db: Session, supplier_id: int, tenant_id: int, company_id: int) -> Supplier:
    supplier = (
        db.query(Supplier)
        .filter(
            Supplier.id == supplier_id,
            Supplier.tenant_id == tenant_id,
            Supplier.company_id == company_id,
            Supplier.deleted_at.is_(None),
        )
        .first()
    )
    if not supplier:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Proveedor no encontrado")
    return supplier


def create_supplier(
    db: Session, payload: SupplierCreate, tenant_id: int, company_id: int, user_id: str | None = None
) -> Supplier:
    supplier = Supplier(
        **payload.model_dump(),
        tenant_id=tenant_id,
        company_id=company_id,
        created_by=user_id,
        updated_by=user_id,
    )
    db.add(supplier)
    db.commit()
    db.refresh(supplier)
    return supplier


def update_supplier(
    db: Session,
    supplier_id: int,
    payload: SupplierUpdate,
    tenant_id: int,
    company_id: int,
    user_id: str | None = None,
) -> Supplier:
    supplier = get_supplier(db, supplier_id, tenant_id, company_id)
    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(supplier, field, value)
    supplier.updated_by = user_id
    db.commit()
    db.refresh(supplier)
    return supplier


def delete_supplier(db: Session, supplier_id: int, tenant_id: int, company_id: int) -> None:
    supplier = get_supplier(db, supplier_id, tenant_id, company_id)
    supplier.deleted_at = datetime.now(timezone.utc)
    db.commit()
