ALTER TABLE purchase_orders
ADD COLUMN IF NOT EXISTS outlet_id UUID REFERENCES outlets(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_purchase_orders_outlet_id
ON purchase_orders(outlet_id);

WITH movement_outlets AS (
    SELECT
        poi.purchase_order_id,
        MIN(im.outlet_id::text)::uuid AS outlet_id
    FROM inventory_movements im
    JOIN purchase_order_items poi ON im.purchase_order_item_id = poi.id
    WHERE im.outlet_id IS NOT NULL
      AND im.purchase_order_item_id IS NOT NULL
    GROUP BY poi.purchase_order_id
    HAVING COUNT(DISTINCT im.outlet_id) = 1
)
UPDATE purchase_orders po
SET outlet_id = movement_outlets.outlet_id
FROM movement_outlets
WHERE po.id = movement_outlets.purchase_order_id
  AND po.outlet_id IS NULL;

WITH candidate_item_outlets AS (
    SELECT
        poi.purchase_order_id,
        i.outlet_id
    FROM purchase_order_items poi
    JOIN ingredients i ON poi.ingredient_id = i.id
    WHERE i.outlet_id IS NOT NULL

    UNION ALL

    SELECT
        poi.purchase_order_id,
        u.outlet_id
    FROM purchase_order_items poi
    JOIN units u ON poi.unit_id = u.id
    WHERE u.outlet_id IS NOT NULL
), item_outlets AS (
    SELECT
        purchase_order_id,
        MIN(outlet_id::text)::uuid AS outlet_id
    FROM candidate_item_outlets
    GROUP BY purchase_order_id
    HAVING COUNT(DISTINCT outlet_id) = 1
)
UPDATE purchase_orders po
SET outlet_id = item_outlets.outlet_id
FROM item_outlets
WHERE po.id = item_outlets.purchase_order_id
  AND po.outlet_id IS NULL;

WITH single_outlet_organizations AS (
    SELECT
        organization_id,
        MIN(id::text)::uuid AS outlet_id
    FROM outlets
    GROUP BY organization_id
    HAVING COUNT(*) = 1
)
UPDATE purchase_orders po
SET outlet_id = single_outlet_organizations.outlet_id
FROM single_outlet_organizations
WHERE po.organization_id = single_outlet_organizations.organization_id
  AND po.outlet_id IS NULL;
