"""Filter presets API — save/load/delete user-specific filter combinations."""

import json

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

from app.core.dependencies import get_current_user
from app.database import get_db
from app.models.user import FilterPreset, User
from app.schemas.filter_preset import FilterPresetCreate, FilterPresetResponse, FilterValues

router = APIRouter()

MAX_PRESETS_PER_USER = 10


@router.get("/", response_model=list[FilterPresetResponse])
def list_presets(
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user),
):
    """Return all filter presets for the current user."""
    presets = (
        db.query(FilterPreset)
        .filter(FilterPreset.user_id == user.id)
        .order_by(FilterPreset.created_at.desc())
        .all()
    )
    result = []
    for p in presets:
        filters = json.loads(p.filters) if isinstance(p.filters, str) else p.filters
        result.append(FilterPresetResponse(
            id=p.id,
            name=p.name,
            filters=FilterValues(**filters),
            created_at=p.created_at,
        ))
    return result


@router.post("/", response_model=FilterPresetResponse, status_code=status.HTTP_201_CREATED)
def create_preset(
    data: FilterPresetCreate,
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user),
):
    """Create a new filter preset for the current user."""
    count = db.query(FilterPreset).filter(FilterPreset.user_id == user.id).count()
    if count >= MAX_PRESETS_PER_USER:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Maximal {MAX_PRESETS_PER_USER} gespeicherte Filter erlaubt.",
        )

    if not data.name.strip():
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail="Name darf nicht leer sein.",
        )

    preset = FilterPreset(
        user_id=user.id,
        name=data.name.strip()[:100],
        filters=json.dumps(data.filters.model_dump(exclude_none=True)),
    )
    db.add(preset)
    db.commit()
    db.refresh(preset)

    filters = json.loads(preset.filters)
    return FilterPresetResponse(
        id=preset.id,
        name=preset.name,
        filters=FilterValues(**filters),
        created_at=preset.created_at,
    )


@router.delete("/{preset_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_preset(
    preset_id: int,
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user),
):
    """Delete a filter preset (own presets only)."""
    preset = (
        db.query(FilterPreset)
        .filter(FilterPreset.id == preset_id, FilterPreset.user_id == user.id)
        .first()
    )
    if not preset:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Preset nicht gefunden.")
    db.delete(preset)
    db.commit()
