from typing import Optional

from pydantic import BaseModel, model_validator, ConfigDict

from core.config import get_db
from core.security.exceptions import CoreValidationError
from models import AgeGroup


class AgeGroupBase(BaseModel):
    label: str
    description: Optional[str] = None
    age_start: int
    age_end: int
    is_active: bool = True


class AgeGroupCreate(AgeGroupBase):
    pass

    @model_validator(mode='after')
    def validate_fields(self):
        with get_db() as db:
            if db.query(AgeGroup).where(AgeGroup.age_start == self.age_start, AgeGroup.deleted_at.is_(None),
                                        AgeGroup.age_end == self.age_end).count() > 0:
                raise CoreValidationError("Age Group already exists.")
        return self


class AgeGroupUpdate(AgeGroupBase):
    id: int

    @model_validator(mode='after')
    def validate_fields(self):
        with get_db() as db:
            if db.query(AgeGroup).where(AgeGroup.age_start == self.age_start, AgeGroup.age_end == self.age_end,
                                        AgeGroup.deleted_at.is_(None),
                                        AgeGroup.id != self.id).count() > 0:
                raise CoreValidationError("Age Group already exists.")
        return self


class AgeGroupResponse(AgeGroupBase):
    id: int
    model_config = ConfigDict(from_attributes=True)
