ALTER TABLE "PurchaseOrder" ADD COLUMN "projectId" TEXT REFERENCES "Project"("id") ON DELETE SET NULL ON UPDATE CASCADE;

CREATE INDEX "PurchaseOrder_projectId_issueDate_idx" ON "PurchaseOrder"("projectId", "issueDate");

UPDATE "WorkOrder"
SET "projectId" = (
  SELECT "Project"."id"
  FROM "Project"
  WHERE "Project"."salesOrderId" = "WorkOrder"."salesOrderId"
  ORDER BY "Project"."createdAt" ASC
  LIMIT 1
)
WHERE "projectId" IS NULL
  AND "salesOrderId" IS NOT NULL
  AND EXISTS (
    SELECT 1
    FROM "Project"
    WHERE "Project"."salesOrderId" = "WorkOrder"."salesOrderId"
  );

UPDATE "PurchaseOrder"
SET "projectId" = (
  SELECT "Project"."id"
  FROM "PurchaseOrderLine"
  INNER JOIN "Project" ON "Project"."salesOrderId" = "PurchaseOrderLine"."salesOrderId"
  WHERE "PurchaseOrderLine"."purchaseOrderId" = "PurchaseOrder"."id"
    AND "PurchaseOrderLine"."salesOrderId" IS NOT NULL
  ORDER BY "Project"."createdAt" ASC
  LIMIT 1
)
WHERE "projectId" IS NULL
  AND EXISTS (
    SELECT 1
    FROM "PurchaseOrderLine"
    INNER JOIN "Project" ON "Project"."salesOrderId" = "PurchaseOrderLine"."salesOrderId"
    WHERE "PurchaseOrderLine"."purchaseOrderId" = "PurchaseOrder"."id"
      AND "PurchaseOrderLine"."salesOrderId" IS NOT NULL
  );
