-- Backfill prefix snapshots from revision_materialized_prefix.
-- prefix_snapshot_row.prefix is TEXT (revision_materialized_prefix.prefix since 000003).

ALTER TABLE prefix_snapshot_row
    ALTER COLUMN prefix TYPE TEXT USING prefix::text;

WITH new_snaps AS (
    INSERT INTO prefix_snapshot (id, content_hash)
    SELECT gen_random_uuid(),
        substr(replace(cr.id::text, '-', '') || replace(cr.id::text, '-', ''), 1, 64)
    FROM config_revision cr
    WHERE cr.prefix_snapshot_id IS NULL
      AND EXISTS (
          SELECT 1 FROM revision_materialized_prefix rmp WHERE rmp.revision_id = cr.id
      )
    RETURNING id, content_hash
)
UPDATE config_revision cr
SET prefix_snapshot_id = ns.id
FROM new_snaps ns
WHERE cr.prefix_snapshot_id IS NULL
  AND ns.content_hash = substr(replace(cr.id::text, '-', '') || replace(cr.id::text, '-', ''), 1, 64);

INSERT INTO prefix_snapshot_row (snapshot_id, ord, prefix, community_id, source)
SELECT cr.prefix_snapshot_id,
    (row_number() OVER (PARTITION BY cr.id ORDER BY rmp.id) - 1)::int,
    rmp.prefix,
    rmp.community_id,
    rmp.source
FROM config_revision cr
JOIN revision_materialized_prefix rmp ON rmp.revision_id = cr.id
WHERE cr.prefix_snapshot_id IS NOT NULL
  AND NOT EXISTS (
      SELECT 1 FROM prefix_snapshot_row psr WHERE psr.snapshot_id = cr.prefix_snapshot_id
  );
