-- Sync budget_come_from = result for all affected tables
-- Run this script when DB connection is restored

-- 1. analysis_5 status_id=1,2,3 (non-research, แผ่นดิน)
UPDATE "BUDGET"."request_budget_analysis_5" a5
SET budget_come_from = rbs3.result
FROM "BUDGET"."request_budget" rb3
JOIN "BUDGET"."request_budget_summarize" rbs3 ON rbs3.request_budget_uid = rb3.request_budget_uid
WHERE rb3.status_id = 3
  AND rb3.project_name_th = a5.project_name_th
  AND a5.api = 'request_budget'
  AND a5.status_id IN (1,2,3)
  AND COALESCE(a5.budget_come_from,'') != COALESCE(rbs3.result,'');

-- 2. analysis_5 status_id=1,2,3 (non-research, รายได้)
UPDATE "BUDGET"."request_budget_analysis_5" a5
SET budget_come_from = rbs3.result
FROM "BUDGET"."request_budget_income" rb3
JOIN "BUDGET"."request_budget_income_summarize" rbs3 ON rbs3.request_budget_income_uid = rb3.request_budget_income_uid
WHERE rb3.status_id = 3
  AND rb3.project_name_th = a5.project_name_th
  AND a5.api = 'request_budget_income'
  AND a5.status_id IN (1,2,3)
  AND COALESCE(a5.budget_come_from,'') != COALESCE(rbs3.result,'');

-- 3. analysis_5_research (via project_name_th join)
UPDATE "BUDGET"."request_budget_analysis_5_research" a5r
SET budget_come_from = rbs3.result
FROM "BUDGET"."request_budget" rb3
JOIN "BUDGET"."request_budget_summarize" rbs3 ON rbs3.request_budget_uid = rb3.request_budget_uid
WHERE rb3.status_id = 3
  AND rb3.project_name_th = a5r.project_name_th
  AND COALESCE(a5r.budget_come_from,'') != COALESCE(rbs3.result,'');

-- 4. change_project_detail (แผ่นดิน)
UPDATE "BUDGET"."change_project_detail" cpd
SET budget_come_from = rbs3.result
FROM "BUDGET"."request_budget" rb3
JOIN "BUDGET"."request_budget_summarize" rbs3 ON rbs3.request_budget_uid = rb3.request_budget_uid
WHERE rb3.status_id = 3
  AND rb3.project_name_th = cpd.project_name_th
  AND (cpd.api = 'request_budget' OR cpd.api IS NULL)
  AND COALESCE(cpd.budget_come_from,'') != COALESCE(rbs3.result,'');

-- 5. change_project_detail (รายได้)
UPDATE "BUDGET"."change_project_detail" cpd
SET budget_come_from = rbs3.result
FROM "BUDGET"."request_budget_income" rb3
JOIN "BUDGET"."request_budget_income_summarize" rbs3 ON rbs3.request_budget_income_uid = rb3.request_budget_income_uid
WHERE rb3.status_id = 3
  AND rb3.project_name_th = cpd.project_name_th
  AND cpd.api = 'request_budget_income'
  AND COALESCE(cpd.budget_come_from,'') != COALESCE(rbs3.result,'');
