from sqlalchemy import Column, Integer, String, Boolean, Table, ForeignKey
from sqlalchemy.orm import relationship
from database import Base


# Many-to-many: prep_zones <-> printers (all printers assigned to a zone)
prep_zone_printers = Table(
    "prep_zone_printers",
    Base.metadata,
    Column("prep_zone_id", Integer, ForeignKey("prep_zones.id"), primary_key=True),
    Column("printer_id",   Integer, ForeignKey("printers.id"),   primary_key=True),
)

# Many-to-many: products <-> prep_zones
product_prep_zones = Table(
    "product_prep_zones",
    Base.metadata,
    Column("product_id",   Integer, ForeignKey("products.id"),    primary_key=True),
    Column("prep_zone_id", Integer, ForeignKey("prep_zones.id"),  primary_key=True),
)


class PrepZone(Base):
    __tablename__ = "prep_zones"

    id                = Column(Integer, primary_key=True, index=True)
    name              = Column(String, nullable=False)
    description       = Column(String, nullable=True)
    notification_name = Column(String, nullable=True)

    # Printer routing
    # auto_print: 'none' | 'master' | 'all'
    auto_print        = Column(String, nullable=False, default='none')
    # master_printer_id: single FK to the "primary" printer (nullable — may not be set yet)
    master_printer_id = Column(Integer, ForeignKey("printers.id"), nullable=True)
    master_copies     = Column(Integer, nullable=False, default=1)
    # secondary printers are those in the M2M table that are NOT the master
    secondary_copies  = Column(Integer, nullable=False, default=1)
    # Legacy field kept for backward compat (use master_copies/secondary_copies instead)
    print_copies      = Column(Integer, nullable=False, default=1)

    # Ticket formatting
    # sort_items_by: 'order_time' | 'item_count' | 'alpha'
    sort_items_by     = Column(String, nullable=False, default='order_time')
    group_by_category = Column(Integer, nullable=False, default=0)   # bool as int
    category_order    = Column(String, nullable=False, default='[]') # JSON array of category IDs
    print_checkboxes  = Column(Integer, nullable=False, default=0)   # bool as int

    # KDS bypass / auto-progression
    bypass_pending        = Column(Integer, nullable=False, default=0)  # skip pending+prep → straight to ready
    bypass_kds            = Column(Integer, nullable=False, default=0)  # skip KDS entirely → straight to served (implies bypass_pending)
    auto_ready_to_served  = Column(Integer, nullable=False, default=0)  # when item hits 'done' on KDS → auto-upgrade to served

    # Relationships
    printers = relationship("Printer", secondary=prep_zone_printers, back_populates="prep_zones")
    products = relationship("Product", secondary=product_prep_zones, back_populates="prep_zones")
