"""
Alert Notes Pydantic Schemas
Data models for contextual customer/contact alerts
"""

from pydantic import BaseModel, Field
from typing import Optional, List
from datetime import datetime
from enum import Enum


class EntityType(str, Enum):
    """Entity types that can have alert notes"""
    customer = "customer"
    contact = "contact"


class Severity(str, Enum):
    """Alert severity levels"""
    info = "info"
    warning = "warning"
    critical = "critical"


class RestrictionType(str, Enum):
    """Types of restrictions for alert notes"""
    group = "group"
    user = "user"


class AlertNoteRestriction(BaseModel):
    """Alert note restriction (who can handle the customer/contact)"""
    id: Optional[int] = None
    alert_note_id: int
    restriction_type: RestrictionType
    restriction_id: int  # References groups.id or users.user_id
    restriction_name: Optional[str] = None  # Filled by JOIN in query
    created_at: Optional[datetime] = None


class AlertNoteAcknowledgement(BaseModel):
    """Alert note acknowledgement record"""
    id: Optional[int] = None
    alert_note_id: int
    user_id: int
    user_name: Optional[str] = None  # Filled by JOIN
    acknowledged_at: Optional[datetime] = None


class AlertNoteBase(BaseModel):
    """Base schema for alert notes"""
    entity_type: EntityType
    entity_id: int
    title: str = Field(..., min_length=1, max_length=255)
    message: str = Field(..., min_length=1)
    severity: Severity = Severity.info
    requires_acknowledgement: bool = True
    active: bool = True


class AlertNoteCreate(AlertNoteBase):
    """Schema for creating an alert note"""
    restriction_group_ids: List[int] = []  # List of group IDs
    restriction_user_ids: List[int] = []   # List of user IDs


class AlertNoteUpdate(BaseModel):
    """Schema for updating an alert note"""
    title: Optional[str] = Field(None, min_length=1, max_length=255)
    message: Optional[str] = Field(None, min_length=1)
    severity: Optional[Severity] = None
    requires_acknowledgement: Optional[bool] = None
    active: Optional[bool] = None
    restriction_group_ids: Optional[List[int]] = None
    restriction_user_ids: Optional[List[int]] = None


class AlertNoteFull(AlertNoteBase):
    """Full alert note schema with all relations"""
    id: int
    created_by_user_id: Optional[int] = None
    created_by_user_name: Optional[str] = None  # Filled by JOIN
    created_at: datetime
    updated_at: datetime
    
    # Related data
    restrictions: List[AlertNoteRestriction] = []
    acknowledgements: List[AlertNoteAcknowledgement] = []
    
    # Entity info (filled by JOIN)
    entity_name: Optional[str] = None


class AlertNoteCheck(BaseModel):
    """Response for checking alerts on an entity"""
    has_alerts: bool
    alerts: List[AlertNoteFull]
    user_can_handle: bool  # Whether current user is allowed per restrictions
    user_has_acknowledged: bool = False
