import { APIRequestContext } from '@playwright/test';
import { fromUnitCreateApiResponse, toUnitCreateApiPayload } from '@/manager/modules/unit/unit-mappers';
import { UnitCreateApiResponse, UnitCreateData, UnitMoveToStatus } from '@/manager/modules/unit/unit-types';
import { Unit } from '@/shared/types/unit-types';

export async function createUnitViaApi(request: APIRequestContext, data: UnitCreateData): Promise<Unit> {
  const response = await request.post('/v1/unit', {
    data: toUnitCreateApiPayload(data),
  });

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

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

  return fromUnitCreateApiResponse(body, data);
}

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

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

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

export async function updateUnitStatusViaApi(
  request: APIRequestContext,
  id: number,
  status: UnitMoveToStatus
): Promise<void> {
  const response = await request.put(`/v1/unit/${id}/status`, {
    data: { status, change: 'manually' },
  });

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

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