import { get, post, put } from "./client";
import { ENDPOINTS } from "./endpoints";
import type {
  ActionListResponse,
  ConfFileContent,
  ConfFileCreateRequest,
  ConfFileUpdateRequest,
  ConfFilesResponse,
  FilterListResponse,
  JailConfigFileContent,
  JailConfigFilesResponse,
} from "../types/config";

export async function fetchJailConfigFiles(): Promise<JailConfigFilesResponse> {
  return get<JailConfigFilesResponse>(ENDPOINTS.configJailFiles);
}

export async function createJailConfigFile(
  req: ConfFileCreateRequest,
): Promise<ConfFileContent> {
  return post<ConfFileContent>(ENDPOINTS.configJailFiles, req);
}

export async function fetchJailConfigFileContent(
  filename: string,
): Promise<JailConfigFileContent> {
  return get<JailConfigFileContent>(ENDPOINTS.configJailFile(filename));
}

export async function updateJailConfigFile(
  filename: string,
  req: ConfFileUpdateRequest,
): Promise<void> {
  await put<undefined>(ENDPOINTS.configJailFile(filename), req);
}

export async function setJailConfigFileEnabled(
  filename: string,
  update: { enabled: boolean },
): Promise<void> {
  await put<undefined>(ENDPOINTS.configJailFileEnabled(filename), update);
}

export async function fetchFilterFiles(): Promise<ConfFilesResponse> {
  const result = await get<FilterListResponse>(ENDPOINTS.configFilters);
  return {
    files: result.filters.map((filter) => ({
      name: filter.name,
      filename: filter.filename,
    })),
    total: result.total,
  };
}

export async function fetchFilterFile(
  name: string,
): Promise<ConfFileContent> {
  return get<ConfFileContent>(ENDPOINTS.configFilterRaw(name));
}

export async function updateFilterFile(
  name: string,
  req: ConfFileUpdateRequest,
): Promise<void> {
  await put<undefined>(ENDPOINTS.configFilterRaw(name), req);
}

export async function createFilterFile(
  req: ConfFileCreateRequest,
): Promise<ConfFileContent> {
  return post<ConfFileContent>(ENDPOINTS.configFiltersRaw, req);
}

export async function fetchActionFiles(): Promise<ConfFilesResponse> {
  const result = await get<ActionListResponse>(ENDPOINTS.configActions);
  return {
    files: result.actions.map((action) => ({
      name: action.name,
      filename: action.filename,
    })),
    total: result.total,
  };
}

export async function fetchActionFile(
  name: string,
): Promise<ConfFileContent> {
  return get<ConfFileContent>(ENDPOINTS.configActionRaw(name));
}

export async function updateActionFile(
  name: string,
  req: ConfFileUpdateRequest,
): Promise<void> {
  await put<undefined>(ENDPOINTS.configActionRaw(name), req);
}

export async function createActionFile(
  req: ConfFileCreateRequest,
): Promise<ConfFileContent> {
  return post<ConfFileContent>(ENDPOINTS.configActions, req);
}
