"""Modelos SQLAlchemy para ICEBERG POS."""
from sqlalchemy import Column, String, Integer, Float, Text, DateTime, Boolean, ForeignKey, UniqueConstraint
from sqlalchemy.sql import func
from database import Base


class Package(Base):
    __tablename__ = 'packages'

    id = Column(String, primary_key=True)
    name = Column(String, nullable=False)
    minutes = Column(Integer, nullable=False)
    price = Column(Float, nullable=False)
    color = Column(String, nullable=False, default='all')
    active = Column(Boolean, nullable=False, default=True)
    created_at = Column(DateTime, server_default=func.now())


class Session(Base):
    __tablename__ = 'sessions'

    id = Column(String, primary_key=True)
    package_id = Column(String, ForeignKey('packages.id'), nullable=False)
    status = Column(String, nullable=False, default='pending')
    red_minutes = Column(Integer, nullable=False)
    green_minutes = Column(Integer, nullable=False)
    blue_minutes = Column(Integer, nullable=False)
    payment_method = Column(String, nullable=False, default='cash')
    amount = Column(Float, nullable=False)
    cashier = Column(String, nullable=False, default='default')
    programmed_at = Column(DateTime, nullable=True)
    expires_at = Column(DateTime, nullable=True)
    agent_id = Column(String, nullable=True)
    folio_number = Column(String, nullable=True)
    created_at = Column(DateTime, server_default=func.now())


class AuditLog(Base):
    __tablename__ = 'audit_log'

    id = Column(Integer, primary_key=True, autoincrement=True)
    timestamp = Column(DateTime, server_default=func.now())
    action = Column(String, nullable=False)
    session_id = Column(String, ForeignKey('sessions.id'), nullable=True)
    details = Column(Text, nullable=True)
    cashier = Column(String, nullable=True)


class Agent(Base):
    __tablename__ = 'agents'

    id = Column(String, primary_key=True)              # "pos-quito-01"
    name = Column(String, nullable=False)               # "Caja 1"
    host = Column(String, nullable=False)               # "127.0.0.1" o "10.0.15.10"
    port = Column(Integer, nullable=False, default=5555)
    token = Column(String, nullable=True)               # API key unica
    status = Column(String, nullable=False, default='offline')  # online/offline
    last_heartbeat = Column(DateTime, nullable=True)
    created_at = Column(DateTime, server_default=func.now())
    venue_id = Column(String, nullable=True)            # venue al que pertenece este agente


class FolioCounter(Base):
    """Contador secuencial de folios por venue y fecha."""
    __tablename__ = 'folio_counters'

    id = Column(Integer, primary_key=True, autoincrement=True)
    venue_id = Column(String, nullable=False)
    fecha = Column(String, nullable=False)          # YYYY-MM-DD
    ultimo_numero = Column(Integer, nullable=False, default=0)


class OdooTicket(Base):
    """Tickets de venta de pulseras recibidos desde Odoo."""
    __tablename__ = 'odoo_tickets'

    id = Column(Integer, primary_key=True, autoincrement=True)
    ticket_number = Column(String, nullable=False, unique=True)
    item_name = Column(String, nullable=True)
    quantity = Column(Integer, nullable=False, default=1)
    unit_price = Column(Float, nullable=True)
    total = Column(Float, nullable=False)
    cashier_name = Column(String, nullable=True)
    cashier_id = Column(String, nullable=True)
    pos_session_id = Column(String, nullable=True)
    venue_id = Column(String, nullable=True)
    odoo_timestamp = Column(DateTime, nullable=True)
    matched_session_id = Column(String, ForeignKey('sessions.id'), nullable=True)
    matched_at = Column(DateTime, nullable=True)
    created_at = Column(DateTime, server_default=func.now())


class ComboRegistry(Base):
    """Registro de combos creados en las apps locales (sin asignar aun)."""
    __tablename__ = 'combo_registry'

    id = Column(Integer, primary_key=True, autoincrement=True)
    combo_id = Column(String, nullable=False, unique=True)  # "C-A1B2C3"
    agent_id = Column(String, nullable=False)                # terminal que lo creo
    venue_id = Column(String, nullable=True)                 # venue al que pertenece este combo
    config_json = Column(Text, nullable=True)                # config visual completa (colores, minutos, estilo)
    created_at = Column(DateTime, server_default=func.now())


class TerminalPackage(Base):
    """Combos personalizados asignados a una terminal con nombre y precio."""
    __tablename__ = 'terminal_packages'
    __table_args__ = (
        UniqueConstraint('agent_id', 'combo_id', name='uq_terminal_combo'),
    )

    id = Column(Integer, primary_key=True, autoincrement=True)
    agent_id = Column(String, nullable=False)       # terminal asignada
    combo_id = Column(String, nullable=False)        # "C-A1B2C3"
    name = Column(String, nullable=False)            # "VIP 60 Min"
    price = Column(Float, nullable=False)            # 5.00
    active = Column(Boolean, nullable=False, default=True)
    created_at = Column(DateTime, server_default=func.now())


class SyncQueue(Base):
    __tablename__ = 'sync_queue'

    id = Column(Integer, primary_key=True, autoincrement=True)
    table_name = Column(String, nullable=False)
    record_id = Column(String, nullable=False)
    action = Column(String, nullable=False)
    payload = Column(Text, nullable=False)
    synced = Column(Boolean, nullable=False, default=False)
    created_at = Column(DateTime, server_default=func.now())
