-- +goose Up
-- Materialized boolean entitlements: one row per (pool, resource_key) that has
-- ever been carried by an active provision's boolean rule. `granted` reflects
-- whether at least one active provision currently carries the rule; rows are
-- retained with granted = FALSE on lapse so consumers can observe transitions.
-- Absence of a row means the key was never conferred on the pool.
CREATE TABLE core.boolean_entitlements (
    pool_id UUID NOT NULL,
    resource_key VARCHAR(100) NOT NULL,
    granted BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT pk_boolean_entitlements PRIMARY KEY (pool_id, resource_key),
    CONSTRAINT fk_boolean_entitlements_pool_id FOREIGN KEY (pool_id) REFERENCES core.resource_pools(pool_id),
    CONSTRAINT fk_boolean_entitlements_resource_key FOREIGN KEY (resource_key) REFERENCES core.resource_keys(resource_key)
);

CREATE INDEX idx_boolean_entitlements_resource_key ON core.boolean_entitlements(resource_key);

CREATE TRIGGER trigger_boolean_entitlements_updated_at
    BEFORE UPDATE ON core.boolean_entitlements
    FOR EACH ROW
    EXECUTE FUNCTION public.update_updated_at_column();

-- The init migration's GRANT ON ALL TABLES was point-in-time; new relations
-- need their own grants.
GRANT ALL ON core.boolean_entitlements TO core_owner, core_writer;
GRANT SELECT ON core.boolean_entitlements TO core_reader;

-- +goose Down
DROP TABLE core.boolean_entitlements;
