import { APIRequestContext } from '@playwright/test';
import {
  ProductCreateApiResponse,
  ProductOneTimeCreateData,
  ProductRecurringCreateData,
} from '@/manager/modules/product/product-types';
import {
  fromProductOneTimeCreateApiResponse,
  fromProductRecurringCreateApiResponse,
  toProductOneTimeCreateApiPayload,
  toProductRecurringCreateApiPayload,
} from '@/manager/modules/product/product-mappers';
import { ProductOneTime, ProductRecurring } from '@/shared/types/product-types';
import { syncBillingCatalog } from '@/shared/utils/billing-utils';

export async function createProductOneTimeViaApi(
  request: APIRequestContext,
  data: ProductOneTimeCreateData
): Promise<ProductOneTime> {
  const response = await request.post('/v1/recurring-one-time-product', {
    data: toProductOneTimeCreateApiPayload(data),
  });

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

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

  await syncBillingCatalog();

  return fromProductOneTimeCreateApiResponse(body, data);
}

export async function createProductRecurringViaApi(
  request: APIRequestContext,
  data: ProductRecurringCreateData
): Promise<ProductRecurring> {
  const response = await request.post('/v1/recurring-one-time-product', {
    data: toProductRecurringCreateApiPayload(data),
  });

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

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

  await syncBillingCatalog();

  return fromProductRecurringCreateApiResponse(body, data);
}

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

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

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

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

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

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