'use client';

import { APIError } from '../../_api/generated/helpers';

/**
 * Shared internals for the 2FA hook family (verify / setup / status).
 *
 * Before consolidation each of the three hooks re-implemented error extraction
 * and 6-digit validation slightly differently — three copies that drifted. This
 * module is the single source for both, so every 2FA verb reports errors and
 * validates codes identically.
 */

const TOTP_CODE_LENGTH = 6;

/** A 2FA API error body may carry any of these message-ish fields. */
interface TwoFactorErrorBody {
  error?: unknown;
  detail?: unknown;
  message?: unknown;
  attempts_remaining?: unknown;
}

/**
 * Extract a human-readable message from a thrown error, unwrapping the
 * APIError response body (error → detail → message) before falling back.
 */
export function extractTwoFactorError(err: unknown, fallback: string): string {
  if (err instanceof APIError) {
    const body = (err.response ?? null) as TwoFactorErrorBody | null;
    if (typeof body?.error === 'string') return body.error;
    if (typeof body?.detail === 'string') return body.detail;
    if (typeof body?.message === 'string') return body.message;
    return err.errorMessage ?? err.message;
  }
  if (err instanceof Error) return err.message;
  return fallback;
}

/** Pull `attempts_remaining` off an APIError body, or null if absent. */
export function extractAttemptsRemaining(err: unknown): number | null {
  if (err instanceof APIError) {
    const body = (err.response ?? null) as TwoFactorErrorBody | null;
    if (typeof body?.attempts_remaining === 'number') return body.attempts_remaining;
  }
  return null;
}

/** True when `code` is a well-formed 6-digit TOTP code. */
export function isValidTotpCode(code: string): boolean {
  return !!code && code.length === TOTP_CODE_LENGTH;
}

export { TOTP_CODE_LENGTH };
