import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";
import type { RootState } from "@/store/store";

interface GeneralSettingState {
  currency: string;
  currencyCode: string;
  isLoaded: boolean;
  isLoading: boolean;
}

const initialState: GeneralSettingState = {
  currency: "USD",
  currencyCode: "$",
  isLoaded: false,
  isLoading: false,
};

type SettingItem = { key: string; value: string };

export const fetchGeneralSettings = createAsyncThunk(
  "generalSetting/fetch",
  async (_, { getState, rejectWithValue }) => {
    const state = getState() as { generalSetting: GeneralSettingState };
    if (state.generalSetting.isLoaded) return null;
    try {
      const res = await apiClient.post(API_ENDPOINTS.GENERAL_SETTING);
      const items: SettingItem[] = res.data?.result ?? [];
      const map: Record<string, string> = {};
      items.forEach((item) => {
        map[item.key] = item.value;
      });
      return {
        currency: map["currency"] ?? "USD",
        currencyCode: map["currency_code"] ?? "$",
      };
    } catch {
      return rejectWithValue("Failed to load settings");
    }
  },
);

const generalSettingSlice = createSlice({
  name: "generalSetting",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchGeneralSettings.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(fetchGeneralSettings.fulfilled, (state, action) => {
        state.isLoading = false;
        if (action.payload) {
          state.currency = action.payload.currency;
          state.currencyCode = action.payload.currencyCode;
          state.isLoaded = true;
        }
      })
      .addCase(fetchGeneralSettings.rejected, (state) => {
        state.isLoading = false;
      });
  },
});

export default generalSettingSlice.reducer;
