import uuid
from typing import TYPE_CHECKING

from sqlalchemy import ForeignKey, Integer, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base

if TYPE_CHECKING:
    from app.models.user import User


class VacationBalance(Base):
    __tablename__ = "vacation_balances"
    __table_args__ = (UniqueConstraint("user_id", "year", name="uq_vacation_balance_user_year"),)

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )
    year: Mapped[int] = mapped_column(Integer, nullable=False)
    entitled_days: Mapped[int] = mapped_column(Integer, default=30)   # Grundurlaub
    special_days: Mapped[int] = mapped_column(Integer, default=0)     # Sondertage
    carried_over: Mapped[int] = mapped_column(Integer, default=0)     # Resturlaub aus Vorjahr
    used_days: Mapped[int] = mapped_column(Integer, default=0)        # Verbraucht

    user: Mapped["User"] = relationship("User", lazy="noload")

    @property
    def total_days(self) -> int:
        return self.entitled_days + self.special_days + self.carried_over

    @property
    def remaining_days(self) -> int:
        return self.total_days - self.used_days

    def __repr__(self) -> str:
        return f"<VacationBalance {self.user_id} {self.year}: {self.remaining_days} left>"
