import { APIRequestContext } from '@playwright/test';
import { DiscountCreateApiResponse, DiscountCreateData } from '@/manager/modules/discount/discount-types';
import { fromDiscountCreateApiResponse, toDiscountCreateApiPayload } from '@/manager/modules/discount/discount-mappers';
import { Discount } from '@/shared/types/discount-types';

export async function createDiscountViaApi(request: APIRequestContext, data: DiscountCreateData): Promise<Discount> {
  const response = await request.post('/v1/discount', {
    data: toDiscountCreateApiPayload(data),
  });

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

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

  return fromDiscountCreateApiResponse(body, data);
}

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

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

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