from pydantic import BaseModel, Field
from typing import Optional, List, Dict
from datetime import datetime

class RoleBase(BaseModel):
    name: str = Field(..., description="Role name (e.g. 'Super Admin', 'Manager')")
    description: Optional[str] = Field(None, description="A brief description of the role")
    permissions: Optional[Dict[int, List[str]]] = Field(
        None, description="Mapping of module IDs to allowed actions, e.g. {1: ['read', 'update']}"
    )
    account_id: Optional[str] = Field(
        None, description="Account ID if role is account-specific; null/empty for global roles"
    )
    is_system_default: Optional[bool] = Field(
        False, description="Flag indicating this is a system default role and should not be modified."
    )
    is_global_access: Optional[bool] = Field(
        False, description="Flag indicating whether the role has global access (True) or is limited to its own data (False)."
    )
    is_saas_only: Optional[bool] = Field(
        False, description="Flag indicating whether the role is SaaS-only."
    )

# Add an optional role_id for default/system roles
class RoleCreate(RoleBase):
    role_id: Optional[int] = None

class RoleUpdate(BaseModel):
    name: Optional[str] = Field(None, description="New role name")
    description: Optional[str] = Field(None, description="New description")
    permissions: Optional[Dict[int, List[str]]] = Field(
        None, description="Mapping of module IDs to allowed actions, e.g. {1: ['read', 'update']}"
    )
    is_system_default: Optional[bool] = Field(
        False, description="Flag indicating this is a system default role and should not be modified."
    )
    is_global_access: Optional[bool] = Field(
        False, description="Flag indicating whether the role has global access (True) or is limited to its own data (False)."
    )
    is_saas_only: Optional[bool] = Field(
        False, description="Flag indicating whether the role is SaaS-only."
    )


    # System flags are not updatable via public endpoints.

class Role(RoleBase):
    id: int = Field(..., alias="role_id")  # role_id is now the id
    created_date: datetime
    updated_date: datetime

class RoleListResponse(BaseModel):
    total_count: int
    roles: List[Role]
