import { APIRequestContext } from '@playwright/test';
import { LocationCategoryApiResponse, LocationDetailApiResponse } from '@/manager/modules/location/location-types';
import { LocationCategory } from '@/shared/types/location-types';

export async function fetchLocationCategoriesViaApi(
  request: APIRequestContext,
  locationId: number
): Promise<LocationCategory[]> {
  const response = await request.get(`/v1/location/${locationId}/category`);

  if (!response.ok()) {
    throw new Error(
      `Failed to fetch categories for location ${locationId}: ${response.status()} ${await response.text()}`
    );
  }

  const body = (await response.json()) as LocationCategoryApiResponse;

  return body.data;
}

// The default payment methods a location offers on emailed invoices — the API requires at least one of these
// ids in a send_invoice create payload (the SPA forces the operator to pick them in the create dialog).
export async function fetchLocationDefaultPaymentMethodIdsViaApi(
  request: APIRequestContext,
  locationId: number
): Promise<number[]> {
  const response = await request.get(`/v1/location/${locationId}`);

  if (!response.ok()) {
    throw new Error(`Failed to fetch location ${locationId}: ${response.status()} ${await response.text()}`);
  }

  const body = (await response.json()) as LocationDetailApiResponse;

  return (body.data.location_billing_settings?.default_payment_methods ?? []).map((method) => method.id);
}
