-- Heal dealers whose gscVerificationToken was written as the full HTML meta
-- tag string by the pre-fix code path (see PR #861). For each affected dealer
-- with an active custom domain:
--   1. Null the malformed token so the worker refetches + stores the
--      correctly-extracted code on the next verify_property run.
--   2. Delete any failed register_property jobs that were a consequence of
--      the malformed token (Google API 400 "verification token could not be
--      found"). These are non-retryable terminal records that would otherwise
--      pollute /admin/gsc and the daily-audit forever.
--   3. Enqueue a fresh verify_property to restart the chain under the fixed
--      code. Mirrors enqueueCustomDomainActivation() in lib/gsc-jobs.ts.
--
-- Idempotent: re-running with no malformed tokens left is a no-op (the temp
-- table is empty, so steps 2 and 3 affect zero rows).
--
-- Wrapped in the migration transaction Prisma applies automatically.

CREATE TEMP TABLE _heal_targets AS
SELECT id, "customDomain"
FROM "Dealer"
WHERE "gscVerificationToken" LIKE '<meta%';

-- Step 1: clear the malformed tokens
UPDATE "Dealer"
SET "gscVerificationToken" = NULL
WHERE id IN (SELECT id FROM _heal_targets);

-- Step 2: drop the failed register_property terminal rows for affected dealers
DELETE FROM "GscJob"
WHERE "dealerId" IN (SELECT id FROM _heal_targets)
  AND "type" = 'register_property'
  AND "status" = 'failed';

-- Step 3: enqueue fresh verify_property for affected dealers that still have
-- an active custom domain. ID format mirrors Prisma's @default(cuid()) shape
-- (lowercase alpha+digits, length 25) but is generated via md5 since cuid is
-- a JS-only function. Per-row entropy from md5(random + clock + id) avoids
-- collisions across the (typically small) affected set.
INSERT INTO "GscJob" (
  "id", "type", "dealerId", "payload", "status", "priority",
  "attempts", "maxAttempts", "runAt", "createdAt", "updatedAt"
)
SELECT
  'c' || substring(md5(random()::text || clock_timestamp()::text || id), 1, 24),
  'verify_property',
  id,
  jsonb_build_object('propertyHost', "customDomain"),
  'pending',
  50,
  0,
  5,
  now(),
  now(),
  now()
FROM _heal_targets
WHERE "customDomain" IS NOT NULL
  AND "customDomain" != '';

DROP TABLE _heal_targets;
