# app/routes/categories.py

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

from app.core.database import SessionLocal
from app.core.auth import get_current_user, requires_role
from app.models.user import User
from app.models.product import Product

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


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@router.get("/", response_model=list[str])
def list_categories(db: Session = Depends(get_db)):
    """
    Alle Kategorien (distinct aus Product.category).
    """
    cats = db.query(Product.category).distinct().all()
    return sorted([c[0] for c in cats if c[0]])


@router.put(
    "/rename",
    dependencies=[Depends(requires_role("manager", "admin"))],
)
def rename_category(
    old_name: str,
    new_name: str,
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user),
):
    """
    Kategorie umbenennen: alle Produkte mit old_name -> new_name.
    """
    if not new_name or new_name.lower() == "alle":
        raise HTTPException(status_code=400, detail="Invalid category name")

    updated = (
        db.query(Product)
        .filter(Product.category == old_name)
        .update({"category": new_name})
    )
    if updated == 0:
        raise HTTPException(status_code=404, detail="Category not found")

    db.commit()
    return {"updated": updated, "new_name": new_name}


@router.delete(
    "/",
    dependencies=[Depends(requires_role("manager", "admin"))],
)
def delete_category(
    name: str,
    reassign_to: str | None = None,
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user),
):
    """
    Kategorie löschen.
    - Mit reassign_to: alle Produkte auf neue Kategorie umhängen.
    - Ohne: Kategorie auf NULL setzen.
    """
    q = db.query(Product).filter(Product.category == name)

    if not q.first():
        raise HTTPException(status_code=404, detail="Category not found")

    if reassign_to:
        updated = q.update({"category": reassign_to})
    else:
        updated = q.update({"category": None})

    db.commit()
    return {"updated": updated, "reassigned_to": reassign_to}
