// Member flow helpers — TOTP enroll / step-up / change password.
import { post, checkEnvelope } from './http.js';
import { generateTOTP } from './totp.js';

export function verifyTOTPForPasswordChange(bearer, otpauthUrl, totpCode) {
  const code = totpCode || generateTOTP(otpauthUrl);
  const data = checkEnvelope(
    post(
      '/api/v1/members/me/totp/verify',
      { code, purpose: 'change_password' },
      bearer,
    ),
    'POST /me/totp/verify (change_password)',
  ).data;
  if (!data.step_up_token) {
    throw new Error('verify: missing step_up_token');
  }
  return data.step_up_token;
}

export function enrollTOTP(bearer) {
  const enroll = checkEnvelope(
    post('/api/v1/members/me/totp/enroll-start', null, bearer),
    'POST /me/totp/enroll-start',
  ).data;
  if (!enroll.otpauth_url) {
    throw new Error('enroll-start: missing otpauth_url');
  }
  const code = generateTOTP(enroll.otpauth_url);
  checkEnvelope(
    post('/api/v1/members/me/totp/enroll-confirm', { code }, bearer),
    'POST /me/totp/enroll-confirm',
  );
  return { otpauthUrl: enroll.otpauth_url };
}

export function changePassword(currentPassword, newPassword, bearer, opts = {}) {
  const body = {
    current_password: currentPassword,
    new_password: newPassword,
  };
  if (opts.stepUpToken) body.step_up_token = opts.stepUpToken;
  if (opts.totpCode) body.totp_code = opts.totpCode;
  const res = post('/api/v1/members/me/password', body, bearer);
  return checkEnvelope(res, 'POST /me/password').data;
}
