CREATE TABLE IF NOT EXISTS bazzar_pos.automation_free_item_rules (
    id BIGSERIAL PRIMARY KEY,
    enabled BOOLEAN NOT NULL DEFAULT TRUE,
    min_subtotal NUMERIC(14,2) NOT NULL CHECK (min_subtotal >= 0),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS bazzar_pos.automation_free_item_rule_products (
    id BIGSERIAL PRIMARY KEY,
    rule_id BIGINT NOT NULL REFERENCES bazzar_pos.automation_free_item_rules(id) ON DELETE CASCADE,
    product_id BIGINT NOT NULL REFERENCES bazzar_pos.products(id),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (rule_id, product_id)
);

CREATE INDEX IF NOT EXISTS idx_automation_free_item_rules_enabled
    ON bazzar_pos.automation_free_item_rules(enabled, min_subtotal DESC);
