import uuid
from datetime import datetime
from sqlalchemy import Column, String, DateTime, Date, Text, ForeignKey, Index
from sqlalchemy.orm import relationship
from utils.utils import Base


class Passenger(Base):
    __tablename__ = "passengers"

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    first_name = Column(String(100), nullable=False)
    last_name = Column(String(100), nullable=False)
    email = Column(String(255), nullable=False, unique=True, index=True)
    phone = Column(String(50), nullable=False)
    date_of_birth = Column(Date, nullable=False)
    passport_number = Column(String(50), nullable=True, index=True)
    nationality = Column(String(100), nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

    bookings = relationship("Booking", back_populates="passenger")

    __table_args__ = (
        Index("ix_passengers_email", "email"),
    )


class Booking(Base):
    __tablename__ = "bookings"

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    booking_reference = Column(String(6), nullable=False, unique=True, index=True)
    passenger_id = Column(String(36), ForeignKey("passengers.id", ondelete="RESTRICT"), nullable=False, index=True)
    flight_id = Column(String(36), ForeignKey("flights.id", ondelete="RESTRICT"), nullable=False, index=True)
    seat_id = Column(String(36), ForeignKey("seats.id", ondelete="SET NULL"), nullable=True, index=True)
    fare_class_id = Column(String(36), ForeignKey("fare_classes.id", ondelete="RESTRICT"), nullable=False, index=True)
    booking_status = Column(String(50), nullable=False, index=True)
    total_price = Column(String(50), nullable=False)
    payment_status = Column(String(50), nullable=False, index=True)
    payment_method = Column(String(100), nullable=True)
    booking_date = Column(DateTime, nullable=False)
    special_requests = Column(Text, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

    passenger = relationship("Passenger", back_populates="bookings")
    flight = relationship("Flight", back_populates="bookings")
    seat = relationship("Seat", back_populates="bookings")
    fare_class = relationship("Fareclass", back_populates="bookings")

    __table_args__ = (
        Index("ix_bookings_booking_reference", "booking_reference"),
        Index("ix_bookings_status_date", "booking_status", "booking_date"),
    )