import { createAsyncThunk } from '@reduxjs/toolkit';

import * as api from '../api';
import { withApiError } from '@/utils/api';

export const fetchModulesList = createAsyncThunk(
  'build/fetchModulesList',
  (params: Record<string, string | number>) => api.listModules(params)
);

export const refreshModulesList = createAsyncThunk('build/refreshModulesList', () => api.refreshModulesList());

export const fetchModule = createAsyncThunk(
  'build/fetchModule',
  ({ name, version }: { name: string; version?: string | null }) => api.getModule(name, version)
);

export const fetchModuleInput = createAsyncThunk(
  'build/fetchModuleInput',
  ({ encodedName, name, projectId }: { encodedName?: boolean; name: string; projectId: number | string }) =>
    api.getModuleInput(projectId, name, encodedName)
);

export const saveModuleInput = createAsyncThunk(
  'build/saveModuleInput',
  withApiError(
    ({
      encodedName,
      input,
      name,
      projectId
    }: {
      encodedName?: boolean;
      input: unknown;
      name: string;
      projectId: number | string;
    }) => api.setModuleInput(projectId, name, input, encodedName)
  )
);

// Category previews shown on the project home page (security / compliance).
export const fetchCategoryModules = createAsyncThunk('build/fetchCategoryModules', async (category: string) => {
  const result = await api.listModules({ tag: category, limit: 4, sortColumn: 'downloads', sortDescending: 'true' });
  return { category, modules: result.data };
});
