-- +goose Up
-- +goose StatementBegin
-- 1. Backfill existing milestone rows without roadmap_item_id
UPDATE roadmap_sync_identities
SET roadmap_item_id = replace(substring(roadmap_milestone_path from '[^/]+$'), '.md', '')
WHERE shape = 'milestone' AND (roadmap_item_id = '' OR roadmap_item_id IS NULL);

-- 2. Drop the unique index on milestone path
DROP INDEX IF EXISTS ux_roadmap_sync_identities_milestone_path;

-- 3. Add unique index for milestone canonical id
CREATE UNIQUE INDEX ux_roadmap_sync_identities_milestone_id
    ON roadmap_sync_identities (shape, roadmap_item_id)
    WHERE shape = 'milestone' AND roadmap_item_id <> '';
-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
DROP INDEX IF EXISTS ux_roadmap_sync_identities_milestone_id;

CREATE UNIQUE INDEX ux_roadmap_sync_identities_milestone_path
    ON roadmap_sync_identities (roadmap_milestone_path);
-- +goose StatementEnd
