"""
Spillerpool på organisasjonsnivå (ADR-001: gjenbrukbar på tvers av turneringer).

Kun org-medlemskap kreves (get_authorized_org) — å opprette en spiller i poolen
er organisator-arbeid, ikke noe som forutsetter rostring på et lag.

Utvidet profil (ADR-017): kontakt-/identitetsfelt brukt til å matche en
selvregistrerende spiller mot en allerede organisator-opprettet rad på
e-post (se app/routers/registration.py), og senere til å koble
app_user.id på (app/routers/auth.py sin verify_magic_link).
"""

from datetime import date

from fastapi import APIRouter, Depends
from pydantic import BaseModel, EmailStr, Field

from ..auth import get_authorized_org
from ..db import org_connection
from ..errors import app_error, translate_db_errors

router = APIRouter()


class PlayerCreate(BaseModel):
    display_name: str = Field(min_length=1, max_length=200)
    # Samme grense som ProfileUpdate.handicap_index i auth.py (WHS-maksimum).
    handicap_index: float | None = Field(default=None, ge=-10, le=54)
    gender: str | None = Field(default=None, pattern="^[mfx]$")
    mobile: str | None = Field(default=None, max_length=30)
    email: EmailStr | None = None
    birth_date: date | None = None
    nickname: str | None = Field(default=None, max_length=100)
    country: str | None = Field(default=None, max_length=100)
    club: str | None = Field(default=None, max_length=200)
    club_member_number: str | None = Field(default=None, max_length=50)


class Player(BaseModel):
    id: str
    display_name: str
    handicap_index: float | None
    gender: str | None
    mobile: str | None
    email: str | None
    birth_date: date | None
    nickname: str | None
    country: str | None
    club: str | None
    club_member_number: str | None


_PLAYER_COLUMNS = """
    id::text, display_name, handicap_index::float AS handicap_index, gender,
    mobile, email, birth_date, nickname, country, club, club_member_number
"""


@router.get("/orgs/{organization_id}/players", response_model=list[Player])
async def list_players(
    organization_id: str = Depends(get_authorized_org),
) -> list[Player]:
    async with org_connection(organization_id) as conn:
        rows = await conn.fetch(
            f"SELECT {_PLAYER_COLUMNS} FROM player ORDER BY display_name"
        )
    return [Player(**dict(r)) for r in rows]


@router.post("/orgs/{organization_id}/players", response_model=Player, status_code=201)
async def create_player(
    body: PlayerCreate,
    organization_id: str = Depends(get_authorized_org),
) -> Player:
    async with org_connection(organization_id) as conn, translate_db_errors():
        row = await conn.fetchrow(
            f"""
            INSERT INTO player
                (organization_id, display_name, handicap_index, gender,
                 mobile, email, birth_date, nickname, country, club, club_member_number)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
            RETURNING {_PLAYER_COLUMNS}
            """,
            organization_id,
            body.display_name,
            body.handicap_index,
            body.gender,
            body.mobile,
            body.email.lower() if body.email else None,
            body.birth_date,
            body.nickname,
            body.country,
            body.club,
            body.club_member_number,
        )
    return Player(**dict(row))


class PlayerUpdate(BaseModel):
    """Alle felt valgfrie -- kun de som faktisk sendes med blir endret
    (PATCH-semantikk via Pydantic sin exclude_unset, se update_player).

    Endrer KUN player-raden (spillerpoolen) -- rører ALDRI en allerede
    frosset team_roster.handicap_index_snapshot (ADR-007): en HCP-
    korrigering her slår derfor ikke inn på et lag spilleren allerede er
    rostret på i en turnering, kun ved FREMTIDIG rostring. Fjern og legg
    til spilleren på nytt på laget for å oppdatere en allerede frosset
    snapshot-verdi.
    """

    display_name: str | None = Field(default=None, min_length=1, max_length=200)
    handicap_index: float | None = Field(default=None, ge=-10, le=54)
    gender: str | None = Field(default=None, pattern="^[mfx]$")
    mobile: str | None = Field(default=None, max_length=30)
    email: EmailStr | None = None
    birth_date: date | None = None
    nickname: str | None = Field(default=None, max_length=100)
    country: str | None = Field(default=None, max_length=100)
    club: str | None = Field(default=None, max_length=200)
    club_member_number: str | None = Field(default=None, max_length=50)


@router.patch("/orgs/{organization_id}/players/{player_id}", response_model=Player)
async def update_player(
    player_id: str,
    body: PlayerUpdate,
    organization_id: str = Depends(get_authorized_org),
) -> Player:
    updates = body.model_dump(exclude_unset=True)
    if not updates:
        raise app_error(400, "VALIDATION_FAILED", "Ingen felt å oppdatere.")
    if updates.get("email") is not None:
        updates["email"] = updates["email"].lower()

    set_clauses = [f"{key} = ${i}" for i, key in enumerate(updates, start=1)]
    values = list(updates.values())
    values.append(player_id)

    async with org_connection(organization_id) as conn, translate_db_errors():
        row = await conn.fetchrow(
            f"""
            UPDATE player SET {", ".join(set_clauses)}
            WHERE id = ${len(values)}
            RETURNING {_PLAYER_COLUMNS}
            """,
            *values,
        )
        if row is None:
            raise app_error(404, "NOT_FOUND", "Spilleren finnes ikke.")
    return Player(**dict(row))
