-- Migration 013: Move sourcing_link and standard_cost to revision properties
--
-- These fields are being deduplicated from the items table into revision
-- properties (JSONB). The YAML property_schemas.defaults already defines
-- them, so they belong in the properties system rather than as standalone
-- columns.

-- Step 1: Copy sourcing_link and standard_cost from items into the current
-- revision's properties JSONB for every item that has non-null values.
UPDATE revisions r
SET properties = r.properties
    || CASE WHEN i.sourcing_link IS NOT NULL
            THEN jsonb_build_object('sourcing_link', i.sourcing_link)
            ELSE '{}'::jsonb END
    || CASE WHEN i.standard_cost IS NOT NULL
            THEN jsonb_build_object('standard_cost', i.standard_cost)
            ELSE '{}'::jsonb END
FROM items i
WHERE r.item_id = i.id
  AND r.revision_number = i.current_revision
  AND (i.sourcing_link IS NOT NULL OR i.standard_cost IS NOT NULL);

-- Step 2: Drop the columns from the items table.
ALTER TABLE items DROP COLUMN sourcing_link;
ALTER TABLE items DROP COLUMN standard_cost;
