"""Telegram account domain model — Pydantic v2 with ORM compatibility."""

from __future__ import annotations

import uuid
from datetime import datetime
from typing import Any

from pydantic import field_validator

from repo_core.base.models import DomainModel


class TelegramAccount(DomainModel):
    """Telegram account entity — Pydantic representation.

    Built with ``from_attributes=True`` so it can be constructed directly
    from SQLAlchemy ORM objects or database rows.
    """

    id: uuid.UUID
    phone_number: str
    external_id: str | None = None
    username: str | None = None
    display_name: str | None = None
    session_encrypted: str
    account_metadata: dict[str, Any] = {}
    is_active: bool = True
    is_platform_manager: bool = False
    status: str = "active"
    flood_wait_until: datetime | None = None
    last_active_at: datetime | None = None
    leased_until: datetime | None = None
    leased_by: str | None = None
    created_at: datetime | None = None
    updated_at: datetime | None = None

    @field_validator("is_active", "is_platform_manager", mode="before")
    @classmethod
    def _coerce_none_to_default(cls, v: Any) -> bool:
        """Coerce None → False so legacy rows with NULL don't break validation."""
        if v is None:
            return False
        return v  # type: ignore[return-value]

    @property
    def platform(self) -> str:
        return "telegram"
