// smoke: POST /api/v1/auth/register/resume
//
// Covers:
//   happy — 未完成註冊帳號重寄 registration OTP
//   404   — member 不存在（28301000）
//   404   — tenant 不存在（29301000）
//   409   — 帳號已驗證（28309000）
//   400   — 缺少 email
//   429   — OTP 重送冷卻（29604000）
import { sleep } from 'k6';
import { post, checkError } from '../lib/http.js';
import { cfg } from '../lib/config.js';
import {
  makeIdentity,
  registerEmail,
  registerAndConfirm,
  registerResume,
} from '../lib/auth.js';

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

export default function () {
  // happy: register 但不 confirm → 等冷卻後 resume 取得新 challenge
  const pending = makeIdentity('resume-happy');
  const reg = registerEmail({
    email: pending.email,
    password: pending.password,
    displayName: pending.displayName,
  });
  sleep(cfg.resendCooldownSeconds + 1);
  const resumed = registerResume({ email: pending.email });
  if (!resumed.challenge_id) {
    throw new Error('register/resume happy: missing challenge_id');
  }
  if (resumed.uid !== reg.uid) {
    throw new Error(`register/resume happy: uid mismatch ${resumed.uid} vs ${reg.uid}`);
  }

  // 404 member not found
  checkError(
    post('/api/v1/auth/register/resume', {
      tenant_slug: cfg.tenantSlug,
      email: `no-such-${Date.now()}@k6.local`,
    }),
    'POST /auth/register/resume (member not found)',
    404,
    28301000,
  );

  // 404 tenant not found
  checkError(
    post('/api/v1/auth/register/resume', {
      tenant_slug: 'no-such-tenant-slug',
      email: pending.email,
    }),
    'POST /auth/register/resume (tenant not found)',
    404,
    29301000,
  );

  // 409 already verified
  const verified = registerAndConfirm();
  checkError(
    post('/api/v1/auth/register/resume', {
      tenant_slug: cfg.tenantSlug,
      email: verified.identity.email,
    }),
    'POST /auth/register/resume (already verified)',
    409,
    28309000,
  );

  // 400 missing email
  const missing = post('/api/v1/auth/register/resume', { tenant_slug: cfg.tenantSlug });
  if (missing.status !== 400) {
    throw new Error(`register/resume missing email: expected 400 got ${missing.status}`);
  }

  // 429 resend cooldown — 連續兩次 resume 同一 unverified 帳號
  const cooldownUser = makeIdentity('resume-cooldown');
  registerEmail({
    email: cooldownUser.email,
    password: cooldownUser.password,
    displayName: cooldownUser.displayName,
  });
  sleep(cfg.resendCooldownSeconds + 1);
  registerResume({ email: cooldownUser.email });
  checkError(
    post('/api/v1/auth/register/resume', {
      tenant_slug: cfg.tenantSlug,
      email: cooldownUser.email,
    }),
    'POST /auth/register/resume (resend cooldown)',
    429,
    29604000,
  );
  sleep(cfg.resendCooldownSeconds + 1);
  registerResume({ email: cooldownUser.email });
}
