import { APIRequestContext } from '@playwright/test';
import { CustomerCreateApiResponse, CustomerCreateData } from '@/manager/modules/customer/customer-types';
import { fromCustomerCreateApiResponse, toCustomerCreateApiPayload } from '@/manager/modules/customer/customer-mappers';
import { Customer } from '@/shared/types/customer-types';

export async function createCustomerViaApi(request: APIRequestContext, data: CustomerCreateData): Promise<Customer> {
  const response = await request.post('/v1/customer', {
    data: toCustomerCreateApiPayload(data),
  });

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

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

  return fromCustomerCreateApiResponse(body, data);
}

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

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

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