ALTER TABLE public.profiles
  ADD COLUMN IF NOT EXISTS client_onboarded_at timestamptz;

COMMENT ON COLUMN public.profiles.client_onboarded_at IS
  'Timestamp when a client portal user completed their one-time password setup.';

ALTER TABLE public.client_invites
  ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup',
  ADD COLUMN IF NOT EXISTS used_at timestamptz,
  ADD COLUMN IF NOT EXISTS cancelled_at timestamptz,
  ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz;

COMMENT ON COLUMN public.client_invites.invite_type IS
  'Invite lifecycle type. setup = first-time password onboarding token.';
COMMENT ON COLUMN public.client_invites.used_at IS
  'Timestamp when the setup token was consumed.';
COMMENT ON COLUMN public.client_invites.cancelled_at IS
  'Timestamp when a pending setup invite was cancelled.';
COMMENT ON COLUMN public.client_invites.setup_completed_at IS
  'Timestamp when password setup completed successfully.';

CREATE UNIQUE INDEX IF NOT EXISTS idx_client_invites_pending_setup_email_tablo
  ON public.client_invites (tablo_id, invited_email)
  WHERE is_pending = true AND invite_type = 'setup';

CREATE INDEX IF NOT EXISTS idx_client_invites_token_pending
  ON public.client_invites (invite_token, is_pending);
