// Journey: business email verification end-to-end
//
// Endpoints exercised:
//   POST /api/v1/auth/register
//   POST /api/v1/auth/register/confirm
//   POST /api/v1/members/me/verifications/email/start
//   POST /api/v1/members/me/verifications/email/confirm
//   GET  /api/v1/members/me   (verify business_email_verified flag is true)
import { get, post, checkEnvelope } from '../lib/http.js';
import { registerAndConfirm } from '../lib/auth.js';
import { fetchEmailOTP } from '../lib/otp.js';
import { unique } from '../lib/config.js';

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

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

  // Use a fresh business email distinct from the registration one so the
  // verify OTP can be distinguished from the registration OTP in MailHog.
  const businessEmail = `${unique('biz')}@k6.local`;
  const since = Date.now() - 1000; // tolerate slight clock skew

  const startRes = post(
    '/api/v1/members/me/verifications/email/start',
    { target: businessEmail },
    bearer,
  );
  const start = checkEnvelope(startRes, 'POST /me/verifications/email/start').data;
  if (!start.challenge_id) throw new Error('email/start: missing challenge_id');

  const code = fetchEmailOTP(businessEmail, { since });

  const confirmRes = post(
    '/api/v1/members/me/verifications/email/confirm',
    { challenge_id: start.challenge_id, code },
    bearer,
  );
  checkEnvelope(confirmRes, 'POST /me/verifications/email/confirm');

  const me = checkEnvelope(get('/api/v1/members/me', bearer), 'GET /members/me (post-verify)').data;
  if (me.business_email !== businessEmail) {
    throw new Error(`business_email not set: got=${me.business_email}`);
  }
  if (me.business_email_verified !== true) {
    throw new Error(`business_email_verified should be true: got=${me.business_email_verified}`);
  }
}
