from datetime import datetime
from pydantic import BaseModel, field_validator
from typing import List, Optional


# Base schema for common fields, including tags
class CalendarEventBase(BaseModel):
    title: str
    description: Optional[str] = None
    start: datetime
    end: Optional[datetime] = None
    location: Optional[str] = None
    color: Optional[str] = None  # Assuming color exists
    all_day: Optional[bool] = False  # Add all_day field, default to False
    tags: Optional[List[str]] = None  # Add optional tags

    @field_validator("tags", mode="before")
    @classmethod
    def tags_validate_null_string(cls, v):
        if v == "Null":
            return None
        return v


# Schema for creating an event (inherits from Base)
class CalendarEventCreate(CalendarEventBase):
    pass


# Schema for updating an event (all fields optional)
class CalendarEventUpdate(BaseModel):
    title: Optional[str] = None
    description: Optional[str] = None
    start: Optional[datetime] = None
    end: Optional[datetime] = None
    location: Optional[str] = None
    color: Optional[str] = None
    all_day: Optional[bool] = None  # Add all_day field
    tags: Optional[List[str]] = None  # Add optional tags for update

    @field_validator("tags", mode="before")
    @classmethod
    def tags_validate_null_string(cls, v):
        if v == "Null":
            return None
        return v


# Schema for the response (inherits from Base, adds ID and user_id)
class CalendarEventResponse(CalendarEventBase):
    id: int
    user_id: int
    all_day: bool  # Ensure all_day is always present in response
    tags: List[str]  # Keep as List[str], remove default []

    @field_validator("tags", mode="before")
    @classmethod
    def tags_validate_none_to_list(cls, v):
        # If the value from the source object (e.g., ORM model) is None,
        # convert it to an empty list before Pydantic validation.
        if v is None:
            return []
        return v

    class Config:
        from_attributes = True
