import os

from sqlalchemy import Boolean, Column, Date, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import declarative_base, relationship

Base = declarative_base()


# Async SQLAlchemy setup
def get_database_url(config=None):
    db_url = None
    if config and "database" in config and "url" in config["database"]:
        db_url = config["database"]["url"]
    if not db_url:
        db_url = os.environ.get("DATABASE_URL")
    if not db_url:
        db_url = "sqlite+aiosqlite:///alpinebits.db"
    return db_url


class Customer(Base):
    __tablename__ = "customers"
    id = Column(Integer, primary_key=True)
    given_name = Column(String)
    contact_id = Column(String, unique=True)
    surname = Column(String)
    name_prefix = Column(String)
    email_address = Column(String)
    phone = Column(String)
    email_newsletter = Column(Boolean)
    address_line = Column(String)
    city_name = Column(String)
    postal_code = Column(String)
    country_code = Column(String)
    gender = Column(String)
    birth_date = Column(String)
    language = Column(String)
    address_catalog = Column(Boolean)  # Added for XML
    name_title = Column(String)  # Added for XML
    reservations = relationship("Reservation", back_populates="customer")


class Reservation(Base):
    __tablename__ = "reservations"
    id = Column(Integer, primary_key=True)
    customer_id = Column(Integer, ForeignKey("customers.id"))
    unique_id = Column(String(35), unique=True)  # max length 35
    start_date = Column(Date)
    end_date = Column(Date)
    num_adults = Column(Integer)
    num_children = Column(Integer)
    children_ages = Column(String)  # comma-separated
    offer = Column(String)
    created_at = Column(DateTime)
    # Add all UTM fields and user comment for XML
    utm_source = Column(String)
    utm_medium = Column(String)
    utm_campaign = Column(String)
    utm_term = Column(String)
    utm_content = Column(String)
    user_comment = Column(String)
    fbclid = Column(String)
    gclid = Column(String)
    # Add hotel_code and hotel_name for XML
    hotel_code = Column(String)
    hotel_name = Column(String)
    customer = relationship("Customer", back_populates="reservations")


# Table for tracking acknowledged requests by client
class AckedRequest(Base):
    __tablename__ = "acked_requests"
    id = Column(Integer, primary_key=True)
    client_id = Column(String, index=True)
    unique_id = Column(
        String, index=True
    )  # Should match Reservation.form_id or another unique field
    timestamp = Column(DateTime)
