// Journey: enroll TOTP → step-up → change password → login with new password
import { post, checkError } from '../lib/http.js';
import { cfg } from '../lib/config.js';
import { registerAndConfirm, login } from '../lib/auth.js';
import {
  changePassword,
  enrollTOTP,
  verifyTOTPForPasswordChange,
} from '../lib/member.js';
export const options = {
  vus: 1,
  iterations: 1,
  thresholds: { checks: ['rate==1.0'] },
};

export default function () {
  const { identity, tokens } = registerAndConfirm();
  const bearer = { Authorization: `Bearer ${tokens.access_token}` };
  const newPassword = 'K6-ChangePass-8!';

  const { otpauthUrl } = enrollTOTP(bearer);
  const stepUpToken = verifyTOTPForPasswordChange(bearer, otpauthUrl);

  const data = changePassword(identity.password, newPassword, bearer, {
    stepUpToken,
  });
  if (!data.ok) {
    throw new Error('change password journey: expected ok=true');
  }

  const session = login({
    email: identity.email,
    password: newPassword,
    otpauthUrl,
  });
  if (!session.access_token) {
    throw new Error('change password journey: login with new password failed');
  }

  checkError(
    post('/api/v1/auth/login', {
      tenant_slug: cfg.tenantSlug,
      email: identity.email,
      password: identity.password,
    }),
    'POST /auth/login (old password after change)',
    401,
    28501000,
  );
}
