

from sqlalchemy import Column, Integer, String, Float, ForeignKey, DateTime
from sqlalchemy.orm import relationship, declarative_base
from datetime import datetime

Base = declarative_base()

class Waiter(Base):
    __tablename__ = "waiters"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True, nullable=False)
    load = Column(Float, default=0)
    role = Column(String, default="waiter")
    
class Group(Base):
    __tablename__ = "groups"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True, nullable=False)
    products = relationship("Product", back_populates="group")

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True, nullable=False)
    password = Column(String, nullable=False)
    role = Column(String, default="user")

class Product(Base): 
    __tablename__ = "products"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True, nullable=False)
    price = Column(Float, nullable=False)
    cost = Column(Float, nullable=False)
    group_id = Column(Integer, ForeignKey("groups.id"), nullable=False)
    group = relationship("Group", back_populates="products")
    order_products = relationship("OrderProduct", back_populates="product")

class Order(Base):
    __tablename__ = "orders"
    id = Column(Integer, primary_key=True, index=True)
    status = Column(String, default="pending")
    total_price = Column(Float, default=0)
    created_at = Column(DateTime, default=datetime.utcnow)
    table_id = Column(Integer, ForeignKey("tables.id"), nullable=True)
    products = relationship("OrderProduct", back_populates="order")

class OrderProduct(Base):
    __tablename__ = "order_products"
    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(Integer, ForeignKey("orders.id"))
    product_id = Column(Integer, ForeignKey("products.id"))
    quantity = Column(Integer, nullable=False)
    waiter_id = Column(Integer, ForeignKey("waiters.id"), nullable=True)
    status = Column(String, default="esperando")  # esperando, en preparacion, listo
    order = relationship("Order", back_populates="products")
    product = relationship("Product", back_populates="order_products")
    waiter = relationship("Waiter")

class Table(Base):
    __tablename__ = "tables"
    id = Column(Integer, primary_key=True, index=True)
    number = Column(Integer, unique=True, index=True, nullable=False)
    name = Column(String, nullable=True)
    abbreviation = Column(String, nullable=True)
    orders = relationship("Order", backref="table")
    pos_x = Column(Integer, nullable=True)
    pos_y = Column(Integer, nullable=True)