import { apiClient } from './client';
import type {
  C2CallbackHistoryResponse,
  C2Config,
  C2ConfigInput,
  C2TestResult,
  C2CallbacksResponse,
  C2ExecuteInput,
  C2ExecuteResponse,
  C2ImportInput,
  C2ImportResponse,
  C2TasksResponse,
} from './types';

export async function getC2Config(engagementId: number): Promise<C2Config | null> {
  try {
    const { data } = await apiClient.get<C2Config>(`/engagements/${engagementId}/c2-config`);
    return data;
  } catch (err: unknown) {
    const e = err as { response?: { status?: number } };
    if (e?.response?.status === 404) return null;
    throw err;
  }
}

export async function putC2Config(
  engagementId: number,
  input: C2ConfigInput,
): Promise<C2Config> {
  const { data } = await apiClient.put<C2Config>(
    `/engagements/${engagementId}/c2-config`,
    input,
  );
  return data;
}

export async function deleteC2Config(engagementId: number): Promise<void> {
  await apiClient.delete(`/engagements/${engagementId}/c2-config`);
}

export async function testC2Config(engagementId: number): Promise<C2TestResult> {
  const { data } = await apiClient.post<C2TestResult>(
    `/engagements/${engagementId}/c2-config/test`,
  );
  return data;
}

export async function listCallbacks(engagementId: number): Promise<C2CallbacksResponse> {
  const { data } = await apiClient.get<C2CallbacksResponse>(
    `/engagements/${engagementId}/c2/callbacks`,
  );
  return data;
}

export async function executeC2(
  simulationId: number,
  input: C2ExecuteInput,
): Promise<C2ExecuteResponse> {
  const { data } = await apiClient.post<C2ExecuteResponse>(
    `/simulations/${simulationId}/c2/execute`,
    input,
  );
  return data;
}

export async function getC2Tasks(simulationId: number): Promise<C2TasksResponse> {
  const { data } = await apiClient.get<C2TasksResponse>(
    `/simulations/${simulationId}/c2/tasks`,
  );
  return data;
}

export async function listCallbackHistory(
  engagementId: number,
  callbackDisplayId: number,
  params: { page: number; pageSize: number },
): Promise<C2CallbackHistoryResponse> {
  const { data } = await apiClient.get<C2CallbackHistoryResponse>(
    `/engagements/${engagementId}/c2/callbacks/${callbackDisplayId}/history`,
    { params: { page: params.page, page_size: params.pageSize } },
  );
  return data;
}

export async function importC2(
  simulationId: number,
  input: C2ImportInput,
): Promise<C2ImportResponse> {
  const { data } = await apiClient.post<C2ImportResponse>(
    `/simulations/${simulationId}/c2/import`,
    input,
  );
  return data;
}
