// Journey: change password while logged in → login with new password
//
// Endpoints:
//   POST /api/v1/auth/register/confirm path (via registerAndConfirm)
//   POST /api/v1/members/me/password
//   POST /api/v1/auth/login
import { post, checkError } from '../lib/http.js';
import { cfg } from '../lib/config.js';
import { registerAndConfirm, loginStep } from '../lib/auth.js';
import { changePassword } 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 data = changePassword(identity.password, newPassword, bearer);
  if (!data.ok) {
    throw new Error('change password journey: expected ok=true');
  }

  const login = loginStep({
    email: identity.email,
    password: newPassword,
  });
  if (!login.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,
  );
}
