// Journey: 未完成註冊 → resume → confirm OTP
//
// Endpoints:
//   POST /api/v1/auth/register
//   POST /api/v1/auth/register/resume
//   POST /api/v1/auth/register/confirm
//   GET  /api/v1/members/me
import { sleep } from 'k6';
import { get, checkEnvelope } from '../lib/http.js';
import { cfg } from '../lib/config.js';
import {
  makeIdentity,
  registerEmail,
  registerResume,
  confirmRegister,
} from '../lib/auth.js';

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

export default function () {
  const identity = makeIdentity('resume-journey');
  registerEmail({
    email: identity.email,
    password: identity.password,
    displayName: identity.displayName,
  });
  sleep(cfg.resendCooldownSeconds + 1);

  const resumed = registerResume({ email: identity.email });
  const tokens = confirmRegister({
    email: identity.email,
    challengeId: resumed.challenge_id,
  });
  if (!tokens.access_token) {
    throw new Error('register/resume journey: missing access_token after confirm');
  }

  const me = checkEnvelope(
    get('/api/v1/members/me', { Authorization: `Bearer ${tokens.access_token}` }),
    'GET /members/me (after resume confirm)',
  ).data;
  if (me.uid !== tokens.uid) {
    throw new Error('register/resume journey: me.uid mismatch');
  }
  if (me.status !== 'active') {
    throw new Error(`register/resume journey: expected active status, got ${me.status}`);
  }
}
