import {
  categoriesListResponse,
  categoryDetailsResponse,
  type CompanyCategoryRow,
} from "./company-category-fixtures";

/** Subset of Cypress `cy.intercept` request used by this stub (avoids non-exported / deep Cypress types). */
type InterceptRequest = {
  url: string;
  reply(staticResponse: { statusCode: number; body: Record<string, unknown> }): void;
  continue(): void;
};

const CATEGORY_ID_IN_URL = /\/company-categories\/([a-f0-9]{24})(?:\?|\/|$)/i;

/**
 * Stubs GET list and GET single category. Uses `req.url` string matching so all
 * request shapes (query strings, rewritten hosts) are handled consistently.
 */
export function stubCompanyCategoriesReads(
  getCategories: () => CompanyCategoryRow[],
): void {
  const reply = (req: InterceptRequest) => {
    const raw = req.url;
    const detailMatch = raw.match(CATEGORY_ID_IN_URL);
    if (detailMatch) {
      const id = detailMatch[1];
      const cat = getCategories().find((c) => c.id === id);
      req.reply({
        statusCode: 200,
        body: categoryDetailsResponse({
          name: cat?.name ?? "Category",
          description: cat?.description ?? "Default description long enough.",
          thumbnail: cat?.thumbnail ?? "",
        }),
      });
      return;
    }

    if (raw.includes("/company-categories")) {
      req.reply({
        statusCode: 200,
        body: categoriesListResponse(getCategories()),
      });
      return;
    }

    req.continue();
  };

  cy.intercept("GET", /\/api\/proxy\/company-categories/, reply);
  cy.intercept("GET", /\/admin\/v1\/company-categories/, reply);
}
