"""Realtime domain — request/response schemas."""
from __future__ import annotations

from datetime import datetime
from typing import Optional
from uuid import UUID

from pydantic import BaseModel, field_validator


class RealtimeConfigResponse(BaseModel):
    project_id: UUID
    enabled: bool
    max_concurrent_connections: int
    history_enabled: bool
    history_buffer_size: int
    updated_at: Optional[datetime] = None

    model_config = {"from_attributes": True}


class UpdateRealtimeConfigRequest(BaseModel):
    enabled: Optional[bool] = None
    history_enabled: Optional[bool] = None
    history_buffer_size: Optional[int] = None


class ChannelResponse(BaseModel):
    id: UUID
    project_id: UUID
    name: str
    access_policy: str
    rls_filter: bool
    created_at: datetime

    model_config = {"from_attributes": True}


class CreateChannelRequest(BaseModel):
    name: str
    access_policy: str = "authenticated"
    rls_filter: bool = False

    @field_validator("name")
    @classmethod
    def validate_name(cls, v: str) -> str:
        v = v.strip()
        if not v:
            raise ValueError("Channel name must not be empty")
        if not v.startswith("custom:"):
            raise ValueError("Custom channel names must start with 'custom:'")
        slug = v[len("custom:"):]
        if not slug or not slug.replace("-", "").replace("_", "").isalnum():
            raise ValueError("Channel name slug must be alphanumeric (hyphens and underscores allowed)")
        return v

    @field_validator("access_policy")
    @classmethod
    def validate_access_policy(cls, v: str) -> str:
        if v not in ("public", "authenticated", "private"):
            raise ValueError("access_policy must be 'public', 'authenticated', or 'private'")
        return v


class UpdateChannelRequest(BaseModel):
    access_policy: Optional[str] = None
    rls_filter: Optional[bool] = None

    @field_validator("access_policy")
    @classmethod
    def validate_access_policy(cls, v: Optional[str]) -> Optional[str]:
        if v is not None and v not in ("public", "authenticated", "private"):
            raise ValueError("access_policy must be 'public', 'authenticated', or 'private'")
        return v


class RealtimeStatsResponse(BaseModel):
    project_id: UUID
    enabled: bool
    channel_count: int
    max_concurrent_connections: int


class BroadcastRequest(BaseModel):
    channel: str
    event: str
    data: dict = {}
