"""
Authentication schemas for request/response validation
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional
from datetime import datetime


class LoginRequest(BaseModel):
    """Request schema for user login"""
    username: str = Field(..., min_length=1, max_length=50, description="Username")
    password: str = Field(..., min_length=1, description="Password")

    @field_validator('username')
    @classmethod
    def username_not_empty(cls, v: str) -> str:
        """Ensure username is not empty or whitespace"""
        if not v or not v.strip():
            raise ValueError('Username cannot be empty')
        return v.strip()

    @field_validator('password')
    @classmethod
    def password_not_empty(cls, v: str) -> str:
        """Ensure password is not empty"""
        if not v:
            raise ValueError('Password cannot be empty')
        return v

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "username": "admin",
                    "password": "admin123"
                }
            ]
        }
    }


class UserInfo(BaseModel):
    """User information schema (excludes sensitive data)"""
    id: str = Field(..., description="User UUID")
    username: str = Field(..., description="Username")
    role: str = Field(..., description="User role (viewer, operator, administrator)")
    created_at: datetime = Field(..., description="Account creation timestamp")
    updated_at: datetime = Field(..., description="Last update timestamp")

    model_config = {
        "from_attributes": True,
        "json_schema_extra": {
            "examples": [
                {
                    "id": "550e8400-e29b-41d4-a716-446655440000",
                    "username": "admin",
                    "role": "administrator",
                    "created_at": "2025-12-08T10:00:00Z",
                    "updated_at": "2025-12-08T10:00:00Z"
                }
            ]
        }
    }


class TokenResponse(BaseModel):
    """Response schema for successful authentication"""
    access_token: str = Field(..., description="JWT access token")
    refresh_token: str = Field(..., description="JWT refresh token")
    token_type: str = Field(default="bearer", description="Token type (always 'bearer')")
    expires_in: int = Field(..., description="Access token expiration time in seconds")
    user: UserInfo = Field(..., description="Authenticated user information")

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
                    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
                    "token_type": "bearer",
                    "expires_in": 3600,
                    "user": {
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "username": "admin",
                        "role": "administrator",
                        "created_at": "2025-12-08T10:00:00Z",
                        "updated_at": "2025-12-08T10:00:00Z"
                    }
                }
            ]
        }
    }


class LogoutResponse(BaseModel):
    """Response schema for successful logout"""
    message: str = Field(default="Successfully logged out", description="Logout confirmation message")

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "message": "Successfully logged out"
                }
            ]
        }
    }


class RefreshTokenRequest(BaseModel):
    """Request schema for token refresh"""
    refresh_token: str = Field(..., description="Refresh token")

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
                }
            ]
        }
    }


class TokenValidationResponse(BaseModel):
    """Response schema for token validation"""
    valid: bool = Field(..., description="Whether the token is valid")
    user: Optional[UserInfo] = Field(None, description="User information if token is valid")

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "valid": True,
                    "user": {
                        "id": "550e8400-e29b-41d4-a716-446655440000",
                        "username": "admin",
                        "role": "administrator",
                        "created_at": "2025-12-08T10:00:00Z",
                        "updated_at": "2025-12-08T10:00:00Z"
                    }
                }
            ]
        }
    }
