-- Add timestamps to zbggcampaign so UI can show "last change" times.
-- This table is append-only (history is preserved by inserting new rows),
-- so zlins_dttm is the time the assignment row was created.

ALTER TABLE zbggcampaign
  ADD COLUMN IF NOT EXISTS zlins_dttm TIMESTAMPTZ;

ALTER TABLE zbggcampaign
  ADD COLUMN IF NOT EXISTS zlupd_dttm TIMESTAMPTZ;

-- Backfill existing rows (no historical source available). This prevents NULLs
-- and makes the API stable after deploying code that selects these columns.
UPDATE zbggcampaign
SET
  zlins_dttm = COALESCE(zlins_dttm, now()),
  zlupd_dttm = COALESCE(zlupd_dttm, zlins_dttm, now());

ALTER TABLE zbggcampaign
  ALTER COLUMN zlins_dttm SET DEFAULT now();

ALTER TABLE zbggcampaign
  ALTER COLUMN zlupd_dttm SET DEFAULT now();

ALTER TABLE zbggcampaign
  ALTER COLUMN zlins_dttm SET NOT NULL;

ALTER TABLE zbggcampaign
  ALTER COLUMN zlupd_dttm SET NOT NULL;

