from sqlalchemy import Column, Integer, String, Boolean, DateTime, Float, ForeignKey, Text
from sqlalchemy.orm import relationship
from datetime import datetime, timezone
from database import Base


def _utcnow():
    return datetime.now(timezone.utc)


class Tab(Base):
    __tablename__ = "tabs"

    id = Column(Integer, primary_key=True, index=True)
    customer_id = Column(Integer, ForeignKey("customers.id"), nullable=False)
    status = Column(String, default="open", nullable=False)  # open | closed | forgiven
    opened_at = Column(DateTime(timezone=True), default=_utcnow)
    closed_at = Column(DateTime(timezone=True), nullable=True)
    closed_by_id = Column(Integer, ForeignKey("users.id"), nullable=True)
    notes = Column(Text, nullable=True)

    customer = relationship("Customer", foreign_keys=[customer_id])
    closed_by = relationship("User", foreign_keys=[closed_by_id])
    entries = relationship("TabEntry", back_populates="tab", cascade="all, delete-orphan")
    payments = relationship("TabPayment", back_populates="tab", cascade="all, delete-orphan")


class TabEntry(Base):
    """What went ON the tab — a deferred charge."""
    __tablename__ = "tab_entries"

    id = Column(Integer, primary_key=True, index=True)
    tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False)
    order_id = Column(Integer, ForeignKey("orders.id"), nullable=True)
    order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True)
    amount = Column(Float, nullable=False)          # snapshot at time of tab entry
    description = Column(Text, nullable=True)       # auto-generated summary
    created_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    created_at = Column(DateTime(timezone=True), default=_utcnow)

    tab = relationship("Tab", back_populates="entries")
    created_by = relationship("User", foreign_keys=[created_by_id])


class TabPayment(Base):
    """What came OFF the tab — a payment reducing the balance."""
    __tablename__ = "tab_payments"

    id = Column(Integer, primary_key=True, index=True)
    tab_id = Column(Integer, ForeignKey("tabs.id"), nullable=False)
    amount = Column(Float, nullable=False)
    payment_method = Column(String, nullable=True)  # cash | card | other
    received_by_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    notes = Column(Text, nullable=True)
    created_at = Column(DateTime(timezone=True), default=_utcnow)

    tab = relationship("Tab", back_populates="payments")
    received_by = relationship("User", foreign_keys=[received_by_id])
