-- Outlook binding owner/takeover fields + global unique graphEventId
ALTER TABLE "platform_meeting_attendance"."outlook_sync_bindings"
  ADD COLUMN IF NOT EXISTS "owner_user_id" VARCHAR(64),
  ADD COLUMN IF NOT EXISTS "owner_email" VARCHAR(255),
  ADD COLUMN IF NOT EXISTS "sync_from" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;

-- Backfill owner from existing meeting creator, fallback to primary mailbox email
UPDATE "platform_meeting_attendance"."outlook_sync_bindings" b
SET
  owner_user_id = m.creator_id,
  owner_email = COALESCE(u.email, b.owner_email)
FROM "platform_meeting_attendance"."meetings" m
LEFT JOIN "platform_iam"."users" u ON u.id = m.creator_id
WHERE b.meeting_id = m.id
  AND (b.owner_user_id IS NULL OR b.owner_email IS NULL);

UPDATE "platform_meeting_attendance"."outlook_sync_bindings" b
SET owner_email = mb.mailbox_email
FROM "platform_meeting_attendance"."outlook_sync_mailboxes" mb
WHERE b.primary_mailbox_id = mb.id
  AND b.owner_email IS NULL;

ALTER TABLE "platform_meeting_attendance"."outlook_sync_bindings"
  DROP CONSTRAINT IF EXISTS "outlook_sync_bindings_primary_mailbox_id_graph_event_id_key";

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'outlook_sync_bindings_graph_event_id_key'
      AND connamespace = 'platform_meeting_attendance'::regnamespace
  ) THEN
    ALTER TABLE "platform_meeting_attendance"."outlook_sync_bindings"
      ADD CONSTRAINT "outlook_sync_bindings_graph_event_id_key" UNIQUE ("graph_event_id");
  END IF;
END $$;

CREATE INDEX IF NOT EXISTS "outlook_sync_bindings_owner_user_id_idx"
  ON "platform_meeting_attendance"."outlook_sync_bindings" ("owner_user_id");
