import { client } from "@/utils/api";
import { unwrap } from "@/utils/endpoint";
import { URL_CONSTANTS } from "@/constants/URLS";
import type { ApiResponse } from "@/types/apiResponse";
import type {
  CreateDropdownOptionDto,
  CreateDropdownSettingDto,
  DropdownOption,
  DropdownSetting,
  UpdateDropdownOptionDto,
  UpdateDropdownSettingDto,
} from "@/types/dropdownSettings";

const BASE = URL_CONSTANTS.DROPDOWN_SETTINGS.BASE;

export const dropdownSettingsService = {
  list: async (): Promise<DropdownSetting[]> => {
    const response = await client.get<ApiResponse<DropdownSetting[]>>(BASE);
    return unwrap(response.data);
  },

  getById: async (id: string): Promise<DropdownSetting> => {
    const response = await client.get<ApiResponse<DropdownSetting>>(
      URL_CONSTANTS.DROPDOWN_SETTINGS.BY_ID(id),
    );
    return unwrap(response.data);
  },

  getByCode: async (code: string): Promise<DropdownSetting> => {
    const response = await client.get<ApiResponse<DropdownSetting>>(
      URL_CONSTANTS.DROPDOWN_SETTINGS.BY_CODE(code),
    );
    return unwrap(response.data);
  },

  create: async (
    payload: CreateDropdownSettingDto,
  ): Promise<DropdownSetting> => {
    const response = await client.post<ApiResponse<DropdownSetting>>(
      BASE,
      payload,
    );
    return unwrap(response.data);
  },

  update: async (
    id: string,
    payload: UpdateDropdownSettingDto,
  ): Promise<DropdownSetting> => {
    const response = await client.patch<ApiResponse<DropdownSetting>>(
      URL_CONSTANTS.DROPDOWN_SETTINGS.BY_ID(id),
      payload,
    );
    return unwrap(response.data);
  },

  remove: async (id: string): Promise<void> => {
    await client.delete(URL_CONSTANTS.DROPDOWN_SETTINGS.BY_ID(id));
  },

  replaceOptions: async (
    id: string,
    options: CreateDropdownOptionDto[],
  ): Promise<DropdownOption[]> => {
    const response = await client.put<ApiResponse<DropdownOption[]>>(
      URL_CONSTANTS.DROPDOWN_SETTINGS.OPTIONS(id),
      options,
    );
    return unwrap(response.data);
  },

  addOption: async (
    id: string,
    payload: CreateDropdownOptionDto,
  ): Promise<DropdownOption> => {
    const response = await client.post<ApiResponse<DropdownOption>>(
      URL_CONSTANTS.DROPDOWN_SETTINGS.OPTIONS(id),
      payload,
    );
    return unwrap(response.data);
  },

  updateOption: async (
    optionId: string,
    payload: UpdateDropdownOptionDto,
  ): Promise<DropdownOption> => {
    const response = await client.patch<ApiResponse<DropdownOption>>(
      URL_CONSTANTS.DROPDOWN_SETTINGS.OPTION_BY_ID(optionId),
      payload,
    );
    return unwrap(response.data);
  },

  removeOption: async (optionId: string): Promise<void> => {
    await client.delete(URL_CONSTANTS.DROPDOWN_SETTINGS.OPTION_BY_ID(optionId));
  },
};
