// Extract an ERR_* code from a thrown error. Supabase wraps Postgres errors
// as `PostgrestError { message, code, details, hint }`; `auth.signInWithOtp`
// passes the trigger's raise text via `AuthApiError { message }`.
//
// We recognise anything that looks like `ERR_[A-Z0-9_]+`.

const CODE_PATTERN = /ERR_[A-Z0-9_]+/;

export function extractErrorCode(err: unknown): string | null {
  if (!err) return null;

  if (typeof err === 'string') {
    const m = err.match(CODE_PATTERN);
    return m ? m[0] : null;
  }

  if (err instanceof Error) {
    const m = err.message.match(CODE_PATTERN);
    return m ? m[0] : null;
  }

  if (typeof err === 'object') {
    const record = err as Record<string, unknown>;
    const candidates: unknown[] = [record.code, record.message, record.details, record.hint];
    for (const candidate of candidates) {
      if (typeof candidate !== 'string') continue;
      const m = candidate.match(CODE_PATTERN);
      if (m) return m[0];
    }
  }

  return null;
}
