import { APIRequestContext } from '@playwright/test';
import { InsuranceCreateApiResponse, InsuranceCreateData } from '@/manager/modules/insurance/insurance-types';
import {
  fromInsuranceCreateApiResponse,
  toInsuranceCreateApiPayload,
} from '@/manager/modules/insurance/insurance-mappers';
import { Insurance } from '@/shared/types/insurance-types';

export async function createInsuranceViaApi(request: APIRequestContext, data: InsuranceCreateData): Promise<Insurance> {
  const response = await request.post('/v1/recurring-product', {
    data: toInsuranceCreateApiPayload(data),
  });

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

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

  return fromInsuranceCreateApiResponse(body, data);
}

export async function deleteInsuranceViaApi(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 insurance ${id} via API: ${response.status()} ${await response.text()}`);
  }
}
