from fastapi import APIRouter, Depends, HTTPException

from app.auth import require_user, is_admin_user
from app.config import settings
from app.dependencies import get_store
from app.schemas import UserPrefs, MemoryCreate, MemoryOut
from app.store import User

router = APIRouter()


@router.get("/me")
async def get_me(user: User = Depends(require_user)):
    return {
        "user_id": user.id,
        "display_name": user.display_name,
        "external_id": user.external_id,
        "is_admin": user.is_admin or is_admin_user(user),
        "prefs": user.prefs,
        "sso_logout_url": settings.sso_logout_url,
    }


@router.put("/me/prefs")
async def set_my_prefs(payload: UserPrefs, user: User = Depends(require_user)):
    """Setzt dauerhafter Routing-Präferenzen des Nutzers. Merge mit bestehenden Prefs."""
    new = {k: v for k, v in payload.model_dump().items() if v is not None}
    merged = {**user.prefs, **new}
    updated = get_store().set_user_prefs(user.id, merged)
    return {"user_id": updated.id, "prefs": updated.prefs}


@router.get("/me/memories", response_model=list[MemoryOut])
async def list_memories(user: User = Depends(require_user)):
    return get_store().get_memories(user.id)


@router.post("/me/memories", response_model=MemoryOut)
async def add_memory(payload: MemoryCreate, user: User = Depends(require_user)):
    """Speichert einen dauerhaften Fakt/eine Vorliebe ueber den Nutzer."""
    return get_store().add_memory(user.id, payload.content.strip())


@router.delete("/me/memories/{memory_id}")
async def delete_memory(memory_id: int, user: User = Depends(require_user)):
    if not get_store().delete_memory(user.id, memory_id):
        raise HTTPException(status_code=404, detail="Memory not found")
    return {"ok": True, "deleted": memory_id}
