from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.db.session import get_db
from app.schemas.database import MaterialDemandRead, MrpGenerationResult
from app.services.auth import require_authenticated_user
from app.services.sales_planning import generate_mrp_for_order, get_mrp_demands_query

router = APIRouter(dependencies=[Depends(require_authenticated_user)])


@router.get("/mrp-demands", response_model=list[MaterialDemandRead])
def list_mrp_demands(
    sales_order_id: int | None = Query(default=None),
    limit: int = Query(default=50, ge=1, le=200),
    db: Session = Depends(get_db),
) -> list[MaterialDemandRead]:
    stmt = get_mrp_demands_query(limit=limit, sales_order_id=sales_order_id)
    rows = db.execute(stmt).mappings().all()
    return [MaterialDemandRead.model_validate(dict(row)) for row in rows]


@router.post("/generate-mrp/{sales_order_id}", response_model=MrpGenerationResult)
def generate_mrp(sales_order_id: int, db: Session = Depends(get_db)) -> MrpGenerationResult:
    sales_order, demand_rows = generate_mrp_for_order(db, sales_order_id)
    return MrpGenerationResult(
        sales_order_id=sales_order.id,
        order_no=sales_order.order_no,
        generated_count=len(demand_rows),
        demand_rows=demand_rows,
    )
