from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime
from models.api_key import APIKeyScope


class APIKeyCreate(BaseModel):
    name: str
    scopes: List[APIKeyScope]
    expires_at: Optional[datetime] = None
    user_id: Optional[int] = None  # Only admins can specify this


class APIKeyResponse(BaseModel):
    id: int
    user_id: int
    name: str
    scopes: List[str]
    is_active: bool
    expires_at: Optional[datetime]
    last_used_at: Optional[datetime]
    created_at: datetime
    user_email: Optional[str] = None  # Include user email for admin view

    class Config:
        from_attributes = True


class APIKeyWithToken(BaseModel):
    api_key: APIKeyResponse
    token: str  # The actual API key token (only returned on creation)


class APIKeyUpdate(BaseModel):
    name: Optional[str] = None
    scopes: Optional[List[APIKeyScope]] = None
    is_active: Optional[bool] = None
    expires_at: Optional[datetime] = None


class APIKeyUsageLog(BaseModel):
    api_key_id: int
    endpoint: str
    method: str
    timestamp: datetime
    ip_address: Optional[str] = None
    user_agent: Optional[str] = None

    class Config:
        from_attributes = True