from datetime import datetime

from sqlalchemy import JSON, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base


class VenueBookingSettings(Base):
    __tablename__ = "venue_booking_settings"

    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    venue_id: Mapped[int] = mapped_column(ForeignKey("venues.id"), nullable=False, unique=True, index=True)
    turn_duration_minutes: Mapped[int] = mapped_column(Integer, nullable=False, default=120)
    whatsapp_assistant_prompt: Mapped[str] = mapped_column(Text, nullable=False, default="")
    whatsapp_business_account_id: Mapped[str] = mapped_column(Text, nullable=False, default="")
    whatsapp_business_id: Mapped[str] = mapped_column(Text, nullable=False, default="")
    whatsapp_phone_number_id: Mapped[str] = mapped_column(Text, nullable=False, default="")
    whatsapp_access_token: Mapped[str] = mapped_column(Text, nullable=False, default="")
    whatsapp_display_phone_number: Mapped[str] = mapped_column(Text, nullable=False, default="")
    whatsapp_verified_name: Mapped[str] = mapped_column(Text, nullable=False, default="")
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False,
    )

    venue = relationship("Venue")


class WhatsAppBookingSession(Base):
    __tablename__ = "whatsapp_booking_sessions"
    __table_args__ = (
        UniqueConstraint("contact_phone", "venue_id", name="uq_whatsapp_booking_sessions_contact_phone_venue_id"),
    )

    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    contact_phone: Mapped[str] = mapped_column(String(40), nullable=False, index=True)
    venue_id: Mapped[int] = mapped_column(ForeignKey("venues.id"), nullable=False, index=True)
    status: Mapped[str] = mapped_column(String(40), nullable=False, default="collecting")
    draft: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
    reservation_id: Mapped[int | None] = mapped_column(ForeignKey("reservations.id"), nullable=True, index=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False,
    )

    venue = relationship("Venue")
    reservation = relationship("Reservation")
