-- Metadata cleanup migration (manual SQL)
-- Keep tags/type as dedicated columns; remove duplicated metadata keys.

BEGIN;

-- 1) Promote metadata.type -> entries.type when present.
UPDATE entries
SET type = metadata->>'type'
WHERE metadata->>'type' IS NOT NULL
  AND metadata->>'type' <> '';

-- 2) Remove metadata.type.
UPDATE entries
SET metadata = metadata - 'type'
WHERE metadata ? 'type';

-- 3) Remove metadata.environment (duplicated by tags prod/dev).
UPDATE entries
SET metadata = metadata - 'environment'
WHERE metadata ? 'environment';

-- 4) Remove metadata.account when equal to folder.
UPDATE entries
SET metadata = metadata - 'account'
WHERE metadata->>'account' = folder;

-- 5) Normalize manufacturer -> provider.
UPDATE entries
SET metadata = (metadata - 'manufacturer')
    || jsonb_build_object('provider', metadata->>'manufacturer')
WHERE metadata ? 'manufacturer'
  AND NOT metadata ? 'provider';

UPDATE entries
SET metadata = metadata - 'manufacturer'
WHERE metadata ? 'manufacturer'
  AND metadata ? 'provider';

-- 6) Drop ssh_key_format (moved to secrets.type).
UPDATE entries
SET metadata = metadata - 'ssh_key_format'
WHERE metadata ? 'ssh_key_format';

-- 7) Remove display_name when duplicated by name.
UPDATE entries
SET metadata = metadata - 'display_name'
WHERE metadata->>'display_name' = name;

-- 8) Condense server_* metadata into server_ref.
UPDATE entries
SET metadata = metadata
    - 'server_account'
    - 'server_hostname'
    - 'server_location'
    - 'server_public_ip'
    || CASE
        WHEN metadata ? 'server_entry_name'
            THEN jsonb_build_object('server_ref', metadata->>'server_entry_name')
        ELSE '{}'::jsonb
    END
WHERE metadata ? 'server_entry_name' OR metadata ? 'server_account';

UPDATE entries
SET metadata = metadata - 'server_entry_name'
WHERE metadata ? 'server_entry_name';

COMMIT;
