"""اسکیماهای احراز هویت OTP."""
from __future__ import annotations

from typing import Literal
from uuid import UUID

from pydantic import BaseModel, Field, field_validator

from app.utils.phone import normalize_mobile, normalize_otp_digits


class OtpRequestPayload(BaseModel):
    mobile: str = Field(..., min_length=10, max_length=15)
    force_sms: bool = False
    context: Literal["public", "admin"] = "public"

    @field_validator("mobile")
    @classmethod
    def validate_mobile(cls, value: str) -> str:
        return normalize_mobile(value)


class OtpRequestResponse(BaseModel):
    message: str
    expires_in: int
    skipped: bool = False


class OtpVerifyPayload(BaseModel):
    mobile: str = Field(..., min_length=10, max_length=15)
    code: str = Field(..., min_length=4, max_length=8)
    context: Literal["public", "admin"] = "public"
    keycloak_sub: str | None = None
    email: str | None = None

    @field_validator("mobile")
    @classmethod
    def validate_mobile(cls, value: str) -> str:
        return normalize_mobile(value)

    @field_validator("code")
    @classmethod
    def validate_code(cls, value: str) -> str:
        normalized = normalize_otp_digits(value)
        if not normalized:
            raise ValueError("کد تأیید نامعتبر است")
        return normalized


class TokenResponse(BaseModel):
    access_token: str
    refresh_token: str
    token_type: str = "bearer"
    expires_in: int
    is_new_user: bool = False
    user_id: UUID
    role: str
