ALTER TABLE "audit_log"
  ALTER COLUMN "tenant_id" TYPE text USING "tenant_id"::text;
--> statement-breakpoint
ALTER TABLE "audit_log"
  ALTER COLUMN "actor_id" TYPE text USING "actor_id"::text;
--> statement-breakpoint
ALTER TABLE "audit_log"
  ALTER COLUMN "entity_id" TYPE text USING "entity_id"::text;
--> statement-breakpoint
ALTER TABLE "audit_log"
  ALTER COLUMN "actor_type" DROP NOT NULL;
--> statement-breakpoint
ALTER TABLE "audit_log"
  ALTER COLUMN "actor_type" DROP DEFAULT;
--> statement-breakpoint
ALTER TABLE "audit_log"
  ADD COLUMN IF NOT EXISTS "actor_label" text;
--> statement-breakpoint
ALTER TABLE "audit_log"
  ADD COLUMN IF NOT EXISTS "metadata" jsonb;
--> statement-breakpoint
ALTER TABLE "audit_log" DISABLE TRIGGER "audit_log_no_update";
--> statement-breakpoint
UPDATE "audit_log"
SET "actor_label" = CASE
    WHEN "actor_type" = 'api_key' AND "api_key_id" IS NOT NULL THEN 'api_key:' || "api_key_id"::text
    ELSE NULL
  END,
  "metadata" = NULLIF(
    jsonb_strip_nulls(
      jsonb_build_object(
        'apiKeyId', CASE WHEN "api_key_id" IS NOT NULL THEN "api_key_id"::text ELSE NULL END,
        'changes', "changes",
        'requestId', "request_id"
      )
    ),
    '{}'::jsonb
  )
WHERE "actor_label" IS NULL OR "metadata" IS NULL;
--> statement-breakpoint
ALTER TABLE "audit_log" ENABLE TRIGGER "audit_log_no_update";
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "idx_audit_log_tenant_created_idx" ON "audit_log" ("tenant_id", "created_at" DESC);
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "idx_audit_log_tenant_entity_idx" ON "audit_log" ("tenant_id", "entity_type", "entity_id");
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "idx_audit_log_tenant_actor_idx" ON "audit_log" ("tenant_id", "actor_id");
