import { APIRequestContext } from '@playwright/test';
import { fetchLocationCategoriesViaApi } from '@/manager/modules/location/location-api';
import { getLocationCategoryLabel } from '@/shared/utils/location-utils';
import { UnitTypeCreateApiResponse, UnitTypeCreateData } from '@/manager/modules/unit-type/unit-type-types';
import {
  fromUnitTypeCreateApiResponse,
  toUnitTypeCreateApiPayload,
} from '@/manager/modules/unit-type/unit-type-mappers';
import { UnitType } from '@/shared/types/unit-type-types';
import { syncBillingCatalog } from '@/shared/utils/billing-utils';

export async function createUnitTypeViaApi(request: APIRequestContext, data: UnitTypeCreateData): Promise<UnitType> {
  const categories = await fetchLocationCategoriesViaApi(request, data.location.id);
  const categoryIds = data.categories.map((seed) => {
    const label = getLocationCategoryLabel(seed, data.location);
    const match = categories.find((c) => getLocationCategoryLabel(c, data.location) === label);

    if (match?.id == null) {
      throw new Error(`Cannot resolve category "${label}" for location ${data.location.id}`);
    }

    return match.id;
  });

  const response = await request.post('/v1/unit-type', {
    data: toUnitTypeCreateApiPayload(data, categoryIds),
  });

  if (!response.ok()) {
    throw new Error(`Failed to create unit type via API: ${response.status()} ${await response.text()}`);
  }

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

  await syncBillingCatalog();

  return fromUnitTypeCreateApiResponse(body, data);
}

export async function deleteUnitTypeViaApi(request: APIRequestContext, id: number): Promise<void> {
  const response = await request.delete(`/v1/unit-type/${id}`);

  if (response.status() === 404) {
    return;
  }

  if (!response.ok()) {
    throw new Error(`Failed to delete unit type ${id} via API: ${response.status()} ${await response.text()}`);
  }
}
