# backend/app/schemas.py
from datetime import datetime

from pydantic import BaseModel, ConfigDict

from .constants import MatchStatus, TournamentTypes, BracketTypes


class TeamSchema(BaseModel):
    id: int
    name: str
    model_config = ConfigDict(from_attributes=True)


class CourtSchema(BaseModel):
    id: int
    name: str
    model_config = ConfigDict(from_attributes=True)


class TeamCreate(BaseModel):
    name: str


class CourtCreate(BaseModel):
    name: str


class SetScore(BaseModel):
    p1: int
    p2: int


class ScoreReport(BaseModel):
    code: str | None = None
    sets: list[SetScore]


class MatchOut(BaseModel):
    id: str
    match_number: int
    round_number: int
    bracket_type: BracketTypes

    status: MatchStatus
    start_time: datetime | None = None
    court_id: int | None = None

    p1_team_id: int | None = None
    p2_team_id: int | None = None
    winner_team_id: int | None = None

    ref_team_id: int | None = None
    ref_label: str | None = None
    ref_team: TeamSchema | None = None

    winner_next_match_id: str | None = None
    winner_next_match_slot: int | None = None
    loser_next_match_id: str | None = None
    loser_next_match_slot: int | None = None

    sets: list[SetScore] = []

    model_config = ConfigDict(from_attributes=True)


class TournamentCreate(BaseModel):
    name: str
    code: str
    type: TournamentTypes
    timestamp: datetime
    duration: int
    teams: list[str]
    courts: list[int]


class TournamentUpdate(BaseModel):
    name: str | None = None
    code: str | None = None
    timestamp: datetime | None = None
    duration: int | None = None
    type: TournamentTypes | None = None


class TournamentOut(BaseModel):
    id: str
    name: str
    timestamp: datetime
    duration: int
    type: TournamentTypes
    team_count: int
    court_count: int
    model_config = ConfigDict(from_attributes=True)


class TournamentDetail(BaseModel):
    id: str
    name: str
    timestamp: datetime
    type: TournamentTypes
    teams: list[TeamSchema]
    courts: list[CourtSchema]
    matches: list[MatchOut]

    model_config = ConfigDict(from_attributes=True)


class TournamentSettingsResponse(TournamentOut):
    code: str
    teams: list[TeamSchema]
    courts: list[CourtSchema]


class Token(BaseModel):
    access_token: str
    token_type: str
    role: str | None
