ALTER TABLE generation_tasks
    ADD COLUMN operator_id BIGINT REFERENCES users(id);

ALTER TABLE template_assist_tasks
    ADD COLUMN operator_id BIGINT REFERENCES users(id);

ALTER TABLE task_records
    ADD COLUMN operator_id BIGINT REFERENCES users(id);

ALTER TABLE tenant_quota_ledgers
    ADD COLUMN operator_id BIGINT REFERENCES users(id);

ALTER TABLE quota_reservations
    ADD COLUMN operator_id BIGINT REFERENCES users(id),
    ALTER COLUMN resource_id DROP NOT NULL;

ALTER TABLE audit_logs
    ADD COLUMN resource_type VARCHAR(50),
    ADD COLUMN resource_id BIGINT,
    ADD COLUMN request_id VARCHAR(64),
    ADD COLUMN error_message TEXT;

CREATE INDEX idx_generation_task_tenant_operator_created
    ON generation_tasks(tenant_id, operator_id, created_at DESC);

CREATE INDEX idx_template_assist_tasks_tenant_operator_created
    ON template_assist_tasks(tenant_id, operator_id, created_at DESC);

CREATE INDEX idx_task_record_tenant_operator_created
    ON task_records(tenant_id, operator_id, created_at DESC);

CREATE INDEX idx_quota_ledgers_tenant_operator_created
    ON tenant_quota_ledgers(tenant_id, operator_id, created_at DESC);

CREATE INDEX idx_quota_reservations_tenant_operator_created
    ON quota_reservations(tenant_id, operator_id, created_at DESC);

CREATE INDEX idx_audit_tenant_operator_created
    ON audit_logs(tenant_id, operator_id, created_at DESC);

DROP INDEX IF EXISTS uk_template_scope_key_version_active;

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

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