"""Rental request and rental request item models."""
from sqlalchemy import Column, Integer, String, Text, Date, TIMESTAMP, ForeignKey, func, Index
from sqlalchemy.orm import relationship
from app.database import Base


class RentalRequest(Base):
    __tablename__ = "rental_requests"

    id = Column(Integer, primary_key=True, autoincrement=True)
    reference_number = Column(String(32), unique=True, nullable=False)
    event_name = Column(String(255), nullable=False)
    date_start = Column(Date, nullable=False)
    date_end = Column(Date, nullable=False)
    location = Column(String(255))
    person_count = Column(Integer)
    contact_name = Column(String(255), nullable=False)
    contact_company = Column(String(255))
    contact_email = Column(String(255), nullable=False)
    contact_phone = Column(String(64))
    contact_street = Column(String(255))
    contact_postalcode = Column(String(16))
    contact_city = Column(String(128))
    message = Column(Text)
    status = Column(String(32), default="pending")
    rentman_request_id = Column(String(64))
    rentman_sync_status = Column(String(32), default="pending")
    rentman_sync_error = Column(Text)
    created_at = Column(TIMESTAMP, server_default=func.now())

    items = relationship("RentalRequestItem", back_populates="rental_request", cascade="all, delete-orphan")

    __table_args__ = (Index("idx_rental_status", "status"),)


class RentalRequestItem(Base):
    __tablename__ = "rental_request_items"

    id = Column(Integer, primary_key=True, autoincrement=True)
    rental_request_id = Column(Integer, ForeignKey("rental_requests.id", ondelete="CASCADE"), nullable=False)
    equipment_id = Column(Integer, ForeignKey("equipment_cache.id"))
    equipment_name = Column(String(255))
    rentman_equipment_id = Column(String(64))
    quantity = Column(Integer, nullable=False, default=1)
    unit_price = Column(String(20))
    rentman_sync_status = Column(String(32), default="pending")

    rental_request = relationship("RentalRequest", back_populates="items")

    __table_args__ = (Index("idx_rental_items_request", "rental_request_id"),)
