import { APIRequestContext } from '@playwright/test';
import {
  CustomerAdjustBalanceData,
  CustomerCreateApiResponse,
  CustomerCreateData,
} from '@/manager/modules/customer/customer-types';
import {
  fromCustomerCreateApiResponse,
  toCustomerBalanceTransactionApiPayload,
  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 createCustomerBalanceTransactionViaApi(
  request: APIRequestContext,
  customerId: number,
  locationId: number,
  data: CustomerAdjustBalanceData
): Promise<void> {
  const response = await request.post(`/v1/customer/${customerId}/balance-transaction/${locationId}`, {
    data: toCustomerBalanceTransactionApiPayload(data),
  });

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

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()}`);
  }
}
