from datetime import time

from pydantic import BaseModel, model_validator, ConfigDict

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


class TimeSlotBaseSchema(BaseModel):
    start_time: time
    end_time: time
    description: str = None


class TimeSlotCreateSchema(TimeSlotBaseSchema):

    @model_validator(mode='after')
    def validate_time(self):
        if self.start_time >= self.end_time:
            raise CoreValidationError("Invalid time has been chosen!")
        with get_db() as db:
            if db.query(TimeSlot).where(TimeSlot.start_time == self.start_time, TimeSlot.end_time == self.end_time,
                                        TimeSlot.deleted_at.is_(None)).count() > 0:
                raise CoreValidationError("Time slot already exists!")
        return self


class TimeSlotUpdateSchema(TimeSlotBaseSchema):
    id: int

    @model_validator(mode='after')
    def validate_fields(self):
        with get_db() as db:
            if db.query(TimeSlot).where(TimeSlot.start_time == self.start_time, TimeSlot.end_time == self.end_time,
                                        TimeSlot.deleted_at.is_(None),
                                        TimeSlot.id != self.id).count() > 0:
                raise CoreValidationError("Time Slot already exists.")
        return self


class TimeSlotResponseSchema(TimeSlotBaseSchema):
    id: int
    title: str
    model_config = ConfigDict(from_attributes=True)
