"""The Vet Clinic database from HW4, provided for HW6. Do not edit this file.

These are the HW4 classes, with two relationships added (Appointment.animal
and ServiceAtAppt.service) so that an endpoint can follow them. The data is
in vet.db, next to this file.

Import what you need in hw6.py:

    from vet import Animal, PetOwner, SessionDep
"""

from collections.abc import Generator
from datetime import datetime
from decimal import Decimal
from pathlib import Path
from typing import Annotated

from fastapi import Depends
from sqlalchemy import CheckConstraint, Engine, UniqueConstraint, event
from sqlmodel import Field, Relationship, Session, SQLModel, create_engine

DATABASE = Path(__file__).with_name("vet.db")


class Employee(SQLModel, table=True):
    __table_args__ = (CheckConstraint("emp_type IN ('vet', 'groomer', 'other')"),)

    eid: int | None = Field(default=None, primary_key=True)
    name: str = Field(max_length=45)
    address: str | None = Field(default=None, max_length=128)
    emp_type: str = Field(max_length=12)


class PetOwner(SQLModel, table=True):
    __tablename__ = "pet_owner"

    owner_id: int | None = Field(default=None, primary_key=True)
    name: str = Field(max_length=45)
    address: str | None = Field(default=None, max_length=128)

    animals: list["Animal"] = Relationship(back_populates="owner")


class Animal(SQLModel, table=True):
    pet_id: int | None = Field(default=None, primary_key=True)
    name: str = Field(max_length=45)
    species: str = Field(max_length=45)
    owner_id: int = Field(foreign_key="pet_owner.owner_id")

    owner: PetOwner = Relationship(back_populates="animals")


class Appointment(SQLModel, table=True):
    __table_args__ = (
        CheckConstraint("appt_type IN ('exam', 'vaccination', 'surgery', 'grooming')"),
        CheckConstraint(
            "(appt_type = 'grooming' AND groomer_id IS NOT NULL AND vet_id IS NULL) OR "
            "(appt_type <> 'grooming' AND vet_id IS NOT NULL AND groomer_id IS NULL)"
        ),
        UniqueConstraint("vet_id", "date_time"),
        UniqueConstraint("groomer_id", "date_time"),
    )

    appt_id: int | None = Field(default=None, primary_key=True)
    date_time: datetime
    appt_type: str = Field(max_length=12)
    reason: str | None = Field(default=None, max_length=255)
    pet_id: int = Field(foreign_key="animal.pet_id")
    groomer_id: int | None = Field(default=None, foreign_key="employee.eid")
    vet_id: int | None = Field(default=None, foreign_key="employee.eid")

    animal: Animal = Relationship()
    performed: list["ServiceAtAppt"] = Relationship(back_populates="appointment")


class Service(SQLModel, table=True):
    __table_args__ = (CheckConstraint("fee >= 0"),)

    service_id: int | None = Field(default=None, primary_key=True)
    name: str = Field(max_length=45, unique=True)
    fee: Decimal = Field(max_digits=6, decimal_places=2)


class ServiceAtAppt(SQLModel, table=True):
    __tablename__ = "service_at_appt"

    service_id: int = Field(foreign_key="service.service_id", primary_key=True)
    appt_id: int = Field(foreign_key="appointment.appt_id", primary_key=True)

    appointment: Appointment = Relationship(back_populates="performed")
    service: Service = Relationship()


def enforce_foreign_keys(engine: Engine) -> Engine:
    """Make SQLite check foreign keys, as PostgreSQL always does."""

    @event.listens_for(engine, "connect")
    def foreign_keys_on(connection, _record):
        connection.execute("PRAGMA foreign_keys = ON")

    return engine


# Set echo=True to see every statement the endpoints send.
engine = enforce_foreign_keys(create_engine(f"sqlite:///{DATABASE}", echo=False))


def get_session() -> Generator[Session, None, None]:
    """Yield one session per request, and close it when the request ends."""
    with Session(engine) as session:
        yield session


SessionDep = Annotated[Session, Depends(get_session)]
