"""Admin endpoints for World Cup fixture management + auto notifications."""

from __future__ import annotations

from typing import Any, Dict

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

from core.auth import require_admin
from core.db import get_db
from services.worldcup_notifications import sync_and_notify_worldcup_fixtures

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


class WorldCupFixturesIn(BaseModel):
    matches: list[dict[str, Any]]


@router.get("/worldcup/fixtures")
async def get_worldcup_fixtures():
    db = get_db()
    docs = await db.worldcup_fixtures.find({}, {"_id": 0}).to_list(length=5000)
    return {"configured": True, "source": "admin", "matches": docs}


@router.get("/sports/fixtures.php")
async def get_worldcup_fixtures_compat_alias():
    """Compatibility alias used by older app builds and PHP bundle clients."""
    return await get_worldcup_fixtures()


@router.post("/admin/worldcup/fixtures")
async def upsert_worldcup_fixtures(
    body: WorldCupFixturesIn,
    _admin=Depends(require_admin),
):
    try:
        result = await sync_and_notify_worldcup_fixtures({"matches": body.matches})
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    return result
