from sqlalchemy import Column, Integer, String, DateTime, Numeric, Boolean, Text, Enum, ForeignKey, Index
from sqlalchemy.orm import relationship
from datetime import datetime
import enum
from ...shared.config.database import Base

class BookingStatus(str, enum.Enum):
    pending = 'pending'
    confirmed = 'confirmed'
    checked_in = 'checked_in'
    checked_out = 'checked_out'
    cancelled = 'cancelled'

class Booking(Base):
    __tablename__ = 'bookings'
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    booking_number = Column(String(50), unique=True, nullable=False, index=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, index=True)
    room_id = Column(Integer, ForeignKey('rooms.id'), nullable=False, index=True)
    check_in_date = Column(DateTime, nullable=False, index=True)
    check_out_date = Column(DateTime, nullable=False, index=True)
    num_guests = Column(Integer, nullable=False, default=1)
    total_price = Column(Numeric(10, 2), nullable=False)
    original_price = Column(Numeric(10, 2), nullable=True)
    discount_amount = Column(Numeric(10, 2), nullable=True, default=0)
    promotion_code = Column(String(50), nullable=True)
    status = Column(Enum(BookingStatus), nullable=False, default=BookingStatus.pending)
    deposit_paid = Column(Boolean, nullable=False, default=False)
    requires_deposit = Column(Boolean, nullable=False, default=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)
    user = relationship('User', back_populates='bookings')
    room = relationship('Room', back_populates='bookings')
    payments = relationship('Payment', back_populates='booking', cascade='all, delete-orphan')
    invoices = relationship('Invoice', back_populates='booking', cascade='all, delete-orphan')
    service_usages = relationship('ServiceUsage', back_populates='booking', cascade='all, delete-orphan')
    checkin_checkout = relationship('CheckInCheckOut', back_populates='booking', uselist=False)
    group_booking_id = Column(Integer, ForeignKey('group_bookings.id'), nullable=True)
    group_booking = relationship('GroupBooking', back_populates='individual_bookings')
    rate_plan_id = Column(Integer, ForeignKey('rate_plans.id'), nullable=True)
    rate_plan = relationship('RatePlan', back_populates='bookings')
    
    # Composite index for date range queries (availability checks)
    __table_args__ = (
        Index('idx_booking_dates', 'check_in_date', 'check_out_date'),
        Index('idx_booking_user_dates', 'user_id', 'check_in_date', 'check_out_date'),
    )