// Journey: full email registration happy path.
//
// Endpoints exercised:
//   POST /api/v1/auth/register            (RegisterReq)
//   POST /api/v1/auth/register/confirm    (RegisterConfirmReq, OTP via MailHog)
//   GET  /api/v1/members/me               (Bearer)
//   PATCH /api/v1/members/me              (UpdateMemberMeReq)
//   POST /api/v1/auth/logout              (Bearer)
import { get, patch, checkEnvelope } from '../lib/http.js';
import { registerAndConfirm, logout } from '../lib/auth.js';

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

export default function () {
  const { identity, tokens } = registerAndConfirm();
  const bearer = { Authorization: `Bearer ${tokens.access_token}` };

  // GET /members/me
  const meRes = get('/api/v1/members/me', bearer);
  const me = checkEnvelope(meRes, 'GET /members/me');
  if (!me.data || me.data.uid !== tokens.uid) {
    throw new Error(`me.uid mismatch: ${meRes.body}`);
  }

  // PATCH /members/me
  const newName = `${identity.displayName} updated`;
  const patchRes = patch('/api/v1/members/me', {
    display_name: newName,
    language: 'en',
    currency: 'TWD',
  }, bearer);
  const patched = checkEnvelope(patchRes, 'PATCH /members/me');
  if (patched.data.display_name !== newName) {
    throw new Error(`display_name did not update: got=${patched.data.display_name}`);
  }

  // POST /auth/logout
  logout({ accessToken: tokens.access_token });
}
