from typing import List, Any, Dict
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from . import services, dto

router = APIRouter()

@router.get("/", response_model=List[dto.ItemPresetResponse])
def list_item_presets(
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """List all item presets for a company"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    return services.get_presets(db, tenant_id, company_id)

@router.post("/", response_model=dto.ItemPresetResponse)
def create_item_preset(
    data: dto.ItemPresetCreate,
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Create a new item preset"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    return services.create_preset(db, tenant_id, company_id, data)

@router.get("/{preset_id}", response_model=dto.ItemPresetResponse)
def get_item_preset(
    preset_id: int,
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Get a specific item preset"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    preset = services.get_preset_by_id(db, preset_id, tenant_id, company_id)
    if not preset:
        raise HTTPException(status_code=404, detail="Item preset not found")
    return preset

@router.put("/{preset_id}", response_model=dto.ItemPresetResponse)
def update_item_preset(
    preset_id: int,
    data: dto.ItemPresetUpdate,
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Update an item preset"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    preset = services.update_preset(db, preset_id, tenant_id, company_id, data)
    if not preset:
        raise HTTPException(status_code=404, detail="Item preset not found")
    return preset

@router.delete("/{preset_id}")
def delete_item_preset(
    preset_id: int,
    company_id: int = Query(...),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Delete an item preset"""
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    success = services.delete_preset(db, preset_id, tenant_id, company_id)
    if not success:
        raise HTTPException(status_code=404, detail="Item preset not found")
    return {"status": "success", "message": "Preset deleted"}
