-- Migration: migrate_secrets_to_vault_functions
-- Created: 2025-04-23-133127
-- Original: 2025-04-23-133127_migrate_secrets_to_vault_functions

-- Migrate existing secrets linked to data_sources to use the vault functions.
-- This assumes the previous link was via data_sources.id = vault.secrets.id
-- and that data_sources has a nullable UUID column named 'secret_id' to store the new link.

-- Create a temporary table to store the mapping between old IDs and new IDs generated by vault.create_secret
CREATE TEMP TABLE temp_secret_migration (
    old_secret_id UUID PRIMARY KEY,
    data_source_id UUID NOT NULL UNIQUE, -- The data_source.id used as the 'name'
    new_secret_id UUID NOT NULL,         -- The new UUID returned by vault.create_secret
    secret_value TEXT NOT NULL           -- Store the value in case it's needed (e.g., for complex down migration)
);

-- Populate the temporary table by iterating over existing data_sources that have a corresponding secret
-- Assuming the old link was data_sources.id = vault.secrets.id
-- Read the decrypted secret value to pass to the new function
INSERT INTO temp_secret_migration (old_secret_id, data_source_id, new_secret_id, secret_value)
SELECT
    ds.id AS old_secret_id,
    ds.id AS data_source_id,
    -- Call vault.create_secret: Use decrypted value, data_source.id as name, and a description
    vault.create_secret(
        sec.decrypted_secret,
        ds.id::text, -- Use data_source.id as the 'name'
        'Migrated secret for data source ' || ds.id::text -- Add a helpful description
    ) AS new_secret_id,
    sec.decrypted_secret AS secret_value
FROM
    data_sources ds
JOIN
    -- Read the decrypted value using the ID that matches the data_source id
    -- If the join was different (e.g., on data_sources.secret_id), adjust here.
    vault.decrypted_secrets sec ON ds.id = sec.id;

-- Update the data_sources table to point to the newly created secret ID
-- This assumes data_sources has a 'secret_id' column to store the new reference
UPDATE data_sources ds
SET secret_id = tsm.new_secret_id
FROM temp_secret_migration tsm
WHERE ds.id = tsm.data_source_id; -- Match based on the data_source_id

-- Drop the temporary table
DROP TABLE temp_secret_migration;