"""
Pydantic models for admin endpoints
Story 3.6: Documentation OpenAPI (Swagger + ReDoc)
"""

from pydantic import BaseModel, Field
from typing import Optional, Literal, Dict, Any, List


class AdminLoginRequest(BaseModel):
    """Request model for admin login"""
    
    password: str = Field(
        ..., 
        example="admin_secret_password", 
        description="Mot de passe administrateur"
    )

    class Config:
        json_schema_extra = {
            "example": {
                "password": "admin_secret_password"
            }
        }


class AdminLoginData(BaseModel):
    """Admin login response data"""
    
    access_token: str = Field(
        ..., 
        example="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", 
        description="Token d'accès admin (expire dans 24h)"
    )
    token_type: str = Field(
        default="bearer", 
        example="bearer", 
        description="Type de token"
    )
    expires_in: int = Field(
        default=86400, 
        example=86400, 
        description="Durée de validité en secondes"
    )


class AdminLoginResponse(BaseModel):
    """Response model for admin login"""
    
    status: str = Field(default="success", description="Statut de la connexion")
    access_token: str = Field(..., description="Token d'accès admin")
    token_type: str = Field(default="bearer", description="Type de token")
    expires_in: int = Field(default=86400, description="Durée de validité en secondes")
    message: str = Field(default="Login successful", description="Message de confirmation")

    class Config:
        json_schema_extra = {
            "example": {
                "status": "success",
                "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
                "token_type": "bearer",
                "expires_in": 86400,
                "message": "Login successful"
            }
        }


class AdminUserUpdateRequest(BaseModel):
    """Request model for updating user tier"""
    
    plan: Literal["free", "starter", "pro", "business", "enterprise"] = Field(
        ..., 
        example="pro", 
        description="Nouveau plan d'abonnement"
    )

    class Config:
        json_schema_extra = {
            "example": {
                "plan": "pro"
            }
        }


class AdminUserData(BaseModel):
    """User data in admin responses"""
    
    id: str = Field(..., description="Identifiant unique de l'utilisateur")
    email: str = Field(..., description="Adresse email")
    name: str = Field(..., description="Nom de l'utilisateur")
    plan: str = Field(..., description="Plan d'abonnement actuel")
    subscription_status: str = Field(..., description="Statut de l'abonnement")
    docs_translated_this_month: int = Field(..., description="Documents traduits ce mois")
    pages_translated_this_month: int = Field(..., description="Pages traduites ce mois")
    extra_credits: int = Field(..., description="Crédits supplémentaires")
    created_at: str = Field(..., description="Date de création du compte")
    plan_limits: Dict[str, Any] = Field(..., description="Limites du plan actuel")


class AdminUserResponse(BaseModel):
    """Response model for admin user operations"""
    
    data: AdminUserData
    meta: dict = Field(default_factory=dict)

    class Config:
        json_schema_extra = {
            "example": {
                "data": {
                    "id": "usr_abc123def456",
                    "email": "utilisateur@exemple.com",
                    "name": "Jean Dupont",
                    "plan": "pro",
                    "subscription_status": "active",
                    "docs_translated_this_month": 15,
                    "pages_translated_this_month": 42,
                    "extra_credits": 0,
                    "created_at": "2024-01-01T00:00:00Z",
                    "plan_limits": {
                        "docs_per_month": 100,
                        "max_pages_per_doc": 100
                    }
                },
                "meta": {}
            }
        }


class AdminUsersListResponse(BaseModel):
    """Response model for listing users"""
    
    total: int = Field(..., description="Nombre total d'utilisateurs")
    users: List[AdminUserData] = Field(..., description="Liste des utilisateurs")


class AdminDashboardResponse(BaseModel):
    """Response model for admin dashboard"""
    
    timestamp: str = Field(..., description="Timestamp de la réponse")
    status: str = Field(..., description="Statut global du système")
    system: Dict[str, Any] = Field(..., description="Informations système")
    providers: Dict[str, Any] = Field(..., description="Statut des providers")
    cleanup: Dict[str, Any] = Field(..., description="Statut du cleanup")
    rate_limits: Dict[str, Any] = Field(..., description="Statut des rate limits")
    config: Dict[str, Any] = Field(..., description="Configuration actuelle")

    class Config:
        json_schema_extra = {
            "example": {
                "timestamp": "2024-01-15T10:30:00Z",
                "status": "healthy",
                "system": {
                    "memory": {},
                    "disk": {}
                },
                "providers": {
                    "google": {
                        "name": "google",
                        "available": True,
                        "last_check": "2024-01-15T10:29:00Z"
                    }
                },
                "cleanup": {
                    "files_cleaned": 12,
                    "tracked_files_count": 5
                },
                "rate_limits": {
                    "active_clients": 3
                },
                "config": {
                    "max_file_size_mb": 50,
                    "supported_extensions": [".xlsx", ".docx", ".pptx"],
                    "translation_service": "google"
                }
            }
        }


class AdminStatsResponse(BaseModel):
    """Response model for admin statistics"""
    
    users: Dict[str, Any] = Field(..., description="Statistiques utilisateurs")
    translations: Dict[str, Any] = Field(..., description="Statistiques de traduction")
    cache: Dict[str, Any] = Field(..., description="Statistiques du cache")
    config: Dict[str, Any] = Field(..., description="Configuration actuelle")

    class Config:
        json_schema_extra = {
            "example": {
                "users": {
                    "total": 150,
                    "active_this_month": 45,
                    "by_plan": {
                        "free": 100,
                        "pro": 40,
                        "business": 10
                    }
                },
                "translations": {
                    "docs_this_month": 350,
                    "pages_this_month": 1250
                },
                "cache": {
                    "hits": 1500,
                    "misses": 500,
                    "size": 42
                },
                "config": {
                    "translation_service": "google",
                    "max_file_size_mb": 50,
                    "supported_extensions": [".xlsx", ".docx", ".pptx"]
                }
            }
        }


class AdminRevokeApiKeyRequest(BaseModel):
    """Request model for admin API key revocation"""
    
    reason: Optional[str] = Field(
        None, 
        example="Violation des conditions d'utilisation",
        description="Raison de la révocation (optionnel)"
    )

    class Config:
        json_schema_extra = {
            "example": {
                "reason": "Violation des conditions d'utilisation"
            }
        }


class AdminRevokeApiKeyData(BaseModel):
    """Data returned after admin API key revocation"""
    
    id: str = Field(..., description="Identifiant de la clé révoquée")
    revoked: bool = Field(..., description="Confirmation de révocation")
    revoked_at: str = Field(..., description="Date de révocation (ISO 8601)")
    owner_user_id: str = Field(..., description="ID de l'utilisateur propriétaire")
    reason: Optional[str] = Field(None, description="Raison de la révocation")


class AdminRevokeApiKeyResponse(BaseModel):
    """Response model for admin API key revocation"""
    
    data: AdminRevokeApiKeyData
    meta: dict = Field(default_factory=dict)

    class Config:
        json_schema_extra = {
            "example": {
                "data": {
                    "id": "550e8400-e29b-41d4-a716-446655440000",
                    "revoked": True,
                    "revoked_at": "2024-01-15T16:00:00Z",
                    "owner_user_id": "usr_abc123def456",
                    "reason": "Violation des conditions d'utilisation"
                },
                "meta": {}
            }
        }