"""Pydantic models for Entity validation."""

from typing import Optional
from pydantic import Field, field_validator

from .base import ToothFairyModel
from .enums import EntityType
from .validators import validate_hex_color


class EntityCreateModel(ToothFairyModel):
    """Validation model for creating an entity."""

    label: str = Field(..., min_length=1, max_length=255, description="Entity label")
    entity_type: EntityType = Field(default=EntityType.TOPIC, description="Type of entity")
    description: Optional[str] = Field(default=None, description="Entity description")
    emoji: Optional[str] = Field(default=None, max_length=10, description="Entity emoji")
    parent_entity: Optional[str] = Field(default=None, description="Parent entity ID")
    background_color: Optional[str] = Field(default=None, description="Background color for UI")

    @field_validator("background_color")
    @classmethod
    def validate_color(cls, v: Optional[str]) -> Optional[str]:
        if v is not None:
            return validate_hex_color(v)
        return v

    def to_api_payload(self) -> dict:
        payload = {
            "label": self.label,
            "type": self.entity_type.value,
        }
        if self.description is not None:
            payload["description"] = self.description
        if self.emoji is not None:
            payload["emoji"] = self.emoji
        if self.parent_entity is not None:
            payload["parentEntity"] = self.parent_entity
        if self.background_color is not None:
            payload["backgroundColor"] = self.background_color
        return payload


class EntityUpdateModel(ToothFairyModel):
    """Validation model for updating an entity."""

    entity_id: str = Field(..., min_length=1, description="Entity ID to update")
    label: Optional[str] = Field(default=None, min_length=1, max_length=255)
    description: Optional[str] = Field(default=None)
    emoji: Optional[str] = Field(default=None, max_length=10)
    parent_entity: Optional[str] = Field(default=None)
    background_color: Optional[str] = Field(default=None)

    @field_validator("background_color")
    @classmethod
    def validate_color(cls, v: Optional[str]) -> Optional[str]:
        if v is not None:
            return validate_hex_color(v)
        return v

    def to_api_payload(self) -> dict:
        payload = {"id": self.entity_id}
        if self.label is not None:
            payload["label"] = self.label
        if self.description is not None:
            payload["description"] = self.description
        if self.emoji is not None:
            payload["emoji"] = self.emoji
        if self.parent_entity is not None:
            payload["parentEntity"] = self.parent_entity
        if self.background_color is not None:
            payload["backgroundColor"] = self.background_color
        return payload