CREATE TABLE IF NOT EXISTS email_change_requests (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  new_email VARCHAR(255) NOT NULL,
  token_hash VARCHAR(64) NOT NULL,
  expires_at TIMESTAMPTZ NOT NULL,
  confirmed_at TIMESTAMPTZ,
  canceled_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_email_change_requests_token
  ON email_change_requests(token_hash);

CREATE UNIQUE INDEX IF NOT EXISTS idx_email_change_requests_pending_user
  ON email_change_requests(user_id)
  WHERE confirmed_at IS NULL AND canceled_at IS NULL;

CREATE UNIQUE INDEX IF NOT EXISTS idx_email_change_requests_pending_email
  ON email_change_requests(new_email)
  WHERE confirmed_at IS NULL AND canceled_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_email_change_requests_expires
  ON email_change_requests(expires_at)
  WHERE confirmed_at IS NULL AND canceled_at IS NULL;
