import { isNumber } from "es-toolkit";

import type { ExpectationResult } from "./types";

import { mismatchFailure } from "./failure";

export function checkStatusCode(statusCode: number, allowed: Array<number | string>): ExpectationResult {
  const matched = allowed.some((pattern) => {
    if (isNumber(pattern)) return statusCode === pattern;
    const base = parseInt(pattern[0]!, 10) * 100;
    return statusCode >= base && statusCode < base + 100;
  });

  if (!matched) {
    return {
      failure: mismatchFailure(
        "status",
        "status",
        allowed,
        statusCode,
        `status ${statusCode} not in [${allowed.join(", ")}]`,
      ),
      matched: false,
    };
  }
  return { failure: null, matched: true };
}
