DROP INDEX IF EXISTS uk_template_tenant_key_version_active;
DROP INDEX IF EXISTS uk_template_platform_key_version_active;

CREATE UNIQUE INDEX uk_template_scope_key_version_active
    ON article_templates(scope, tenant_id, template_key, version_no)
    WHERE deleted_at IS NULL;

DROP INDEX IF EXISTS idx_audit_tenant_operator_created;
DROP INDEX IF EXISTS idx_quota_reservations_tenant_operator_created;
DROP INDEX IF EXISTS idx_quota_ledgers_tenant_operator_created;
DROP INDEX IF EXISTS idx_task_record_tenant_operator_created;
DROP INDEX IF EXISTS idx_template_assist_tasks_tenant_operator_created;
DROP INDEX IF EXISTS idx_generation_task_tenant_operator_created;

ALTER TABLE audit_logs
    DROP COLUMN IF EXISTS error_message,
    DROP COLUMN IF EXISTS request_id,
    DROP COLUMN IF EXISTS resource_id,
    DROP COLUMN IF EXISTS resource_type;

UPDATE quota_reservations
SET resource_id = 0
WHERE resource_id IS NULL;

ALTER TABLE quota_reservations
    DROP COLUMN IF EXISTS operator_id,
    ALTER COLUMN resource_id SET NOT NULL;

ALTER TABLE tenant_quota_ledgers
    DROP COLUMN IF EXISTS operator_id;

ALTER TABLE task_records
    DROP COLUMN IF EXISTS operator_id;

ALTER TABLE template_assist_tasks
    DROP COLUMN IF EXISTS operator_id;

ALTER TABLE generation_tasks
    DROP COLUMN IF EXISTS operator_id;
