-- Add user-entered payment date to PurchaseOrder
ALTER TABLE "PurchaseOrder" ADD COLUMN "paymentDate" TIMESTAMP(3);

-- Backfill 1: fully-paid POs already carry paidAt — use it as the payment date
UPDATE "PurchaseOrder"
SET "paymentDate" = "paidAt"
WHERE "paidAt" IS NOT NULL AND "paymentDate" IS NULL;

-- Backfill 2: POs that have a payment reference but no payment date yet
-- (e.g. partially-paid) — use the date the payment reference was first recorded,
-- i.e. the earliest PAYMENT_SENT / PARTIAL_PAYMENT_CONFIRMED action.
UPDATE "PurchaseOrder" po
SET "paymentDate" = sub."firstPaymentActionAt"
FROM (
  SELECT "poId", MIN("createdAt") AS "firstPaymentActionAt"
  FROM "POAction"
  WHERE "actionType" IN ('PAYMENT_SENT', 'PARTIAL_PAYMENT_CONFIRMED')
  GROUP BY "poId"
) sub
WHERE po."id" = sub."poId"
  AND po."paymentDate" IS NULL
  AND po."paymentRef" IS NOT NULL;
