from __future__ import annotations

from typing import List
from uuid import UUID

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

from app.database import get_db
from app.models import NeverSuggest, NeverSuggestReason
from app.schemas.never_suggest import NeverSuggestCreate, NeverSuggestRead
from app.security import require_admin


public_router = APIRouter(prefix="/api/never-suggest", tags=["never-suggest"])
admin_router = APIRouter(
    prefix="/api/admin/never-suggest",
    tags=["never-suggest-admin"],
    dependencies=[Depends(require_admin)],
)


def _coerce_reason(raw: str | None) -> NeverSuggestReason | None:
    if raw is None:
        return None
    try:
        return NeverSuggestReason(raw)
    except ValueError:
        raise HTTPException(status_code=422, detail=f"unknown reason: {raw}")


@public_router.get("", response_model=List[NeverSuggestRead])
def list_for_family(
    family_profile_id: UUID = Query(...),
    db: Session = Depends(get_db),
):
    return (
        db.query(NeverSuggest)
        .filter(NeverSuggest.family_profile_id == family_profile_id)
        .all()
    )


@admin_router.post("", response_model=NeverSuggestRead, status_code=status.HTTP_201_CREATED)
def block(payload: NeverSuggestCreate, db: Session = Depends(get_db)):
    row = NeverSuggest(
        family_profile_id=payload.family_profile_id,
        ingredient_id=payload.ingredient_id,
        recipe_id=payload.recipe_id,
        reason=_coerce_reason(payload.reason),
        notes=payload.notes,
    )
    db.add(row)
    db.commit()
    db.refresh(row)
    return row


@admin_router.delete(
    "/{ns_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    response_class=Response,
)
def unblock(ns_id: UUID, db: Session = Depends(get_db)) -> Response:
    row = db.query(NeverSuggest).filter(NeverSuggest.id == ns_id).first()
    if row is None:
        raise HTTPException(status_code=404, detail="never-suggest entry not found")
    db.delete(row)
    db.commit()
    return Response(status_code=204)
