from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.api.deps import AuthSession, require_client_module_access
from app.db.session import get_db
from app.models.mix import Mix
from app.models.product import Product
from app.schemas.product import ProductCostBreakdown, ProductCreate, ProductRead, ProductUpdate
from app.services.costing_engine import calculate_product_cost

router = APIRouter(prefix="/api/products", tags=["products"])


def _serialize_product(product: Product) -> dict:
    return {
        "id": product.id,
        "tenant_id": product.tenant_id,
        "client_name": product.client_name,
        "item_id": product.item_id,
        "name": product.name,
        "mix_id": product.mix_id,
        "mix_name": product.mix.name if product.mix else "",
        "sale_type": product.sale_type,
        "own_bag": product.own_bag,
        "visible": product.visible,
        "unit_of_measure": product.unit_of_measure,
        "items_per_pallet": product.items_per_pallet,
        "bagging_process": product.bagging_process,
        "distributor_margin": product.distributor_margin,
        "wholesale_margin": product.wholesale_margin,
        "notes": product.notes,
        "created_at": product.created_at,
    }


@router.get("", response_model=list[ProductRead])
def list_products(
    limit: int = Query(default=100, ge=1, le=200),
    session: AuthSession = Depends(require_client_module_access("products")),
    db: Session = Depends(get_db),
):
    products = db.scalars(select(Product).where(Product.tenant_id == session.tenant_id).order_by(Product.name).limit(limit)).all()
    return [_serialize_product(product) for product in products]


@router.post("", response_model=ProductRead, status_code=status.HTTP_201_CREATED)
def create_product(payload: ProductCreate, session: AuthSession = Depends(require_client_module_access("products", "edit")), db: Session = Depends(get_db)):
    if db.scalar(select(Mix.id).where(Mix.id == payload.mix_id, Mix.tenant_id == session.tenant_id)) is None:
        raise HTTPException(status_code=404, detail="Mix not found")
    product = Product(tenant_id=session.tenant_id, **payload.model_dump())
    db.add(product)
    db.commit()
    db.refresh(product)
    return _serialize_product(product)


@router.get("/{product_id}", response_model=ProductRead)
def get_product(product_id: int, session: AuthSession = Depends(require_client_module_access("products")), db: Session = Depends(get_db)):
    product = db.scalar(select(Product).where(Product.id == product_id, Product.tenant_id == session.tenant_id))
    if product is None:
        raise HTTPException(status_code=404, detail="Product not found")
    return _serialize_product(product)


@router.patch("/{product_id}", response_model=ProductRead)
def update_product(product_id: int, payload: ProductUpdate, session: AuthSession = Depends(require_client_module_access("products", "edit")), db: Session = Depends(get_db)):
    product = db.scalar(select(Product).where(Product.id == product_id, Product.tenant_id == session.tenant_id))
    if product is None:
        raise HTTPException(status_code=404, detail="Product not found")
    if payload.mix_id is not None and db.scalar(select(Mix.id).where(Mix.id == payload.mix_id, Mix.tenant_id == session.tenant_id)) is None:
        raise HTTPException(status_code=404, detail="Mix not found")
    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(product, field, value)
    db.commit()
    db.refresh(product)
    return _serialize_product(product)


@router.get("/{product_id}/cost-breakdown", response_model=ProductCostBreakdown)
def get_product_cost_breakdown(product_id: int, session: AuthSession = Depends(require_client_module_access("products")), db: Session = Depends(get_db)):
    if db.scalar(select(Product.id).where(Product.id == product_id, Product.tenant_id == session.tenant_id)) is None:
        raise HTTPException(status_code=404, detail="Product not found")
    try:
        return calculate_product_cost(db, product_id)
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc


@router.get("/{product_id}/price-output", response_model=ProductCostBreakdown)
def get_product_price_output(product_id: int, session: AuthSession = Depends(require_client_module_access("products")), db: Session = Depends(get_db)):
    if db.scalar(select(Product.id).where(Product.id == product_id, Product.tenant_id == session.tenant_id)) is None:
        raise HTTPException(status_code=404, detail="Product not found")
    try:
        return calculate_product_cost(db, product_id)
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
