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

import Api from '@/api';

import type {
  DeletedHostsCleanup,
  DuplicateCleanup,
  GroupCleanup,
  HostGroup,
  HostIdentifierOption,
  HostManagementForm,
  InactivityCleanup,
} from './index';

const identifier_url = '/settingsApi/hostIdentifier';
const preferences_url = '/settingsApi/preferences';
const shared_groups_url = '/groups_app/sharedGroups/list';

type PreferencesResponse = {
  inactiveHostsCleanup: InactivityCleanup;
  deletedHostsCleanup: DeletedHostsCleanup;
  duplicateHostnameHostsCleanup: DuplicateCleanup;
  duplicateIpHostsCleanup: DuplicateCleanup;
  groupHostsCleanup: GroupCleanup;
};

export const getHostManagement = createAsyncThunk('hostManagement/get', async () => {
  const [identifierRes, preferencesRes] = await Promise.all([Api.get(identifier_url), Api.get(preferences_url)]);
  const identifierData = identifierRes.data;
  const preferences = (preferencesRes.data ?? {}) as PreferencesResponse;
  return {
    identifier: {
      current: identifierData?.current ?? 'default.sys.fqhost',
      options: (identifierData?.options ?? []) as HostIdentifierOption[],
    },
    ...preferences,
  };
});

export const getHostGroups = createAsyncThunk('hostManagement/getGroups', async () => {
  const { data } = await Api.get(shared_groups_url);
  const items = Array.isArray(data?.data) ? data.data : [];
  return items.map(group => ({ id: String(group.id), name: group.name })) as HostGroup[];
});

export const updateHostManagement = createAsyncThunk(
  'hostManagement/update',
  async (form: HostManagementForm, { rejectWithValue }) => {
    try {
      const { identifier, ...cleanup } = form;
      await Api.put(preferences_url, { hostIdentifier: identifier, ...cleanup });
      notify.success('Host management settings updated.');
      return form;
    } catch (error) {
      notify.error('Failed to update host management settings. Please check the application logs.');
      return rejectWithValue(error);
    }
  }
);
