from sqlalchemy import Column, Integer, String, Date, Boolean, ForeignKey, DateTime
from sqlalchemy.orm import declarative_base, relationship
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
import os

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"))
    form_id = Column(String, unique=True)
    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)
    utm_comment = 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")



class HashedCustomer(Base):
    __tablename__ = "hashed_customers"
    id = Column(Integer, primary_key=True)
    customer_id = Column(Integer)
    hashed_email = Column(String)
    hashed_phone = Column(String)
    hashed_name = Column(String)
    redacted_at = Column(DateTime)
