-- Product recipes table
CREATE TABLE product_recipes (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    organization_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
    outlet_id UUID REFERENCES outlets(id) ON DELETE CASCADE,
    product_id UUID NOT NULL REFERENCES products(id) ON DELETE CASCADE,
    variant_id UUID REFERENCES product_variants(id) ON DELETE CASCADE,
    ingredient_id UUID NOT NULL REFERENCES ingredients(id) ON DELETE CASCADE,
    quantity DECIMAL(12,3) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Indexes
CREATE INDEX idx_product_recipes_organization_id ON product_recipes(organization_id);
CREATE INDEX idx_product_recipes_outlet_id ON product_recipes(outlet_id);
CREATE INDEX idx_product_recipes_product_id ON product_recipes(product_id);
CREATE INDEX idx_product_recipes_variant_id ON product_recipes(variant_id);
CREATE INDEX idx_product_recipes_ingredient_id ON product_recipes(ingredient_id);
CREATE INDEX idx_product_recipes_created_at ON product_recipes(created_at);

-- Unique constraint to prevent duplicate recipe combinations
-- This allows multiple recipes for same product with different variants, or same product with no variant
CREATE UNIQUE INDEX idx_product_recipes_unique ON product_recipes(product_id, COALESCE(variant_id, '00000000-0000-0000-0000-000000000000'::UUID), ingredient_id);