-- Tables table
CREATE TABLE tables (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
    outlet_id UUID NOT NULL REFERENCES outlets(id) ON DELETE CASCADE,
    table_name VARCHAR(100) NOT NULL,
    start_time TIMESTAMP WITH TIME ZONE,
    status VARCHAR(50) DEFAULT 'available' CHECK (status IN ('available', 'occupied', 'reserved', 'cleaning', 'maintenance')),
    order_id UUID REFERENCES orders(id) ON DELETE SET NULL,
    payment_amount DECIMAL(10,2) DEFAULT 0.00 CHECK (payment_amount >= 0),
    position_x DECIMAL(10,2) DEFAULT 0.00,
    position_y DECIMAL(10,2) DEFAULT 0.00,
    capacity INTEGER DEFAULT 4 CHECK (capacity >= 1 AND capacity <= 20),
    is_active BOOLEAN DEFAULT true,
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Indexes
CREATE INDEX idx_tables_organization_id ON tables(organization_id);
CREATE INDEX idx_tables_outlet_id ON tables(outlet_id);
CREATE INDEX idx_tables_order_id ON tables(order_id);
CREATE INDEX idx_tables_status ON tables(status);
CREATE INDEX idx_tables_is_active ON tables(is_active);
CREATE INDEX idx_tables_table_name ON tables(table_name);
CREATE INDEX idx_tables_created_at ON tables(created_at);

-- Unique constraint for table name within an outlet
CREATE UNIQUE INDEX idx_tables_outlet_table_name ON tables(outlet_id, table_name) WHERE is_active = true; 