from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from .. import models, schemas, auth, database

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

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

@router.get("/", response_model=List[schemas.Category])
def get_categories(
    db: Session = Depends(get_db),
    current_user: auth.TokenData = Depends(auth.get_current_user)
):
    """[C-01] List of categories — only for authenticated users."""
    categories = db.query(models.Category).all()
    # Auto-seed if empty with defaults mentioned by user
    if not categories:
        defaults = [
            {"name": "Connectors", "description": "Conectica: cables, adapters, plugs"},
            {"name": "Spare Parts", "description": "Piese de schimb: specific components"},
            {"name": "Tools", "description": "Hand and power tools"},
            {"name": "Consumables", "description": "One-time use items"}
        ]
        for d in defaults:
            cat = models.Category(**d)
            db.add(cat)
        db.commit()
        return db.query(models.Category).all()
    return categories

@router.post("/", response_model=schemas.Category)
def create_category(
    category: schemas.CategoryCreate,
    db: Session = Depends(get_db),
    current_user: auth.TokenData = Depends(auth.get_current_user)
):
    """[C-01] Create category — only for authenticated users."""
    existing = db.query(models.Category).filter(models.Category.name == category.name).first()
    if existing:
        raise HTTPException(status_code=400, detail="Category already exists")

    new_cat = models.Category(**category.model_dump())
    db.add(new_cat)
    db.commit()
    db.refresh(new_cat)
    return new_cat

@router.put("/{cat_id}", response_model=schemas.Category)
def update_category(
    cat_id: int,
    category: schemas.CategoryCreate,
    db: Session = Depends(get_db),
    current_user: auth.TokenData = Depends(auth.get_current_user)
):
    """[C-01] Update category — only for authenticated users."""
    db_cat = db.query(models.Category).filter(models.Category.id == cat_id).first()
    if not db_cat:
        raise HTTPException(status_code=404, detail="Category not found")

    update_data = category.model_dump(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_cat, key, value)

    db.commit()
    db.refresh(db_cat)
    return db_cat

@router.delete("/{cat_id}")
def delete_category(
    cat_id: int,
    db: Session = Depends(get_db),
    current_user: auth.TokenData = Depends(auth.get_current_user)
):
    """[C-01] Delete category — only for authenticated users."""
    cat = db.query(models.Category).filter(models.Category.id == cat_id).first()
    if not cat:
        raise HTTPException(status_code=404, detail="Category not found")

    # Check if items are linked
    linkedItems = db.query(models.Item).filter(models.Item.category_id == cat_id).count()
    if linkedItems > 0:
        raise HTTPException(status_code=400, detail="Cannot delete category with linked items")

    db.delete(cat)
    db.commit()
    return {"message": "Category deleted"}
