// Journey: forgot password → reset → login with new password
//
// Endpoints:
//   POST /api/v1/auth/register + /register/confirm  (setup)
//   POST /api/v1/auth/password/forgot
//   POST /api/v1/auth/password/reset
//   POST /api/v1/auth/login
import { post, checkError } from '../lib/http.js';
import { cfg } from '../lib/config.js';
import { registerAndConfirm, passwordForgot, passwordReset, loginStep } from '../lib/auth.js';
import { fetchEmailOTP } from '../lib/otp.js';

export const options = {
  vus: 1,
  iterations: 1,
  thresholds: { checks: ['rate==1.0'] },
};

export default function () {
  const { identity } = registerAndConfirm();
  const newPassword = 'K6-ResetPass-9!';

  const since = Date.now();
  const forgot = passwordForgot({ email: identity.email });
  const code = fetchEmailOTP(identity.email, { since });
  passwordReset({
    challengeId: forgot.challenge_id,
    code,
    newPassword,
  });

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

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