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

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) {
  const res = post(
    '/api/v1/members/me/password',
    { current_password: currentPassword, new_password: newPassword },
    bearer,
  );
  return checkEnvelope(res, 'POST /me/password').data;
}
