-- Enhance KOL core tables with integrity constraints and missing index.
-- Follow-up to 20260417100000 addressing review findings:
--   1. Composite FK for usage-log audit replay (prompt_id, prompt_revision_no)
--   2. CHECK: active prompts must have a published revision
--   3. Tenant-leading index on kol_packages for list paths

ALTER TABLE kol_usage_logs
    ADD CONSTRAINT fk_kol_usage_logs_prompt_revision
    FOREIGN KEY (prompt_id, prompt_revision_no)
    REFERENCES kol_prompt_revisions(prompt_id, revision_no);

ALTER TABLE kol_prompts
    ADD CONSTRAINT chk_kol_prompts_active_has_published_revision
    CHECK (status <> 'active' OR published_revision_no IS NOT NULL);

CREATE INDEX idx_kol_package_tenant
    ON kol_packages(tenant_id, created_at DESC)
    WHERE deleted_at IS NULL;
