import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { packageService, Package } from "@/services/packageService";

interface PackageState {
  packages: Package[];
  isLoading: boolean;
  error: string | null;
}

const initialState: PackageState = {
  packages: [],
  isLoading: false,
  error: null,
};

export const fetchPackages = createAsyncThunk(
  "packages/fetch",
  async (_, { rejectWithValue, getState }) => {
    try {
      const state = getState() as { generalSetting: { currencyCode: string } };
      const currencyCode = state.generalSetting?.currencyCode ?? "$";
      const res = await packageService.getPackages();
      if (res.status !== 200) return rejectWithValue(res.message);
      return res.result.map((raw) => packageService.mapPackage(raw, res.result, currencyCode));
    } catch (err: unknown) {
      return rejectWithValue(err instanceof Error ? err.message : "Failed to load packages");
    }
  },
);

const packageSlice = createSlice({
  name: "packages",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchPackages.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchPackages.fulfilled, (state, action) => {
        state.isLoading = false;
        state.packages = action.payload;
      })
      .addCase(fetchPackages.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      });
  },
});

export default packageSlice.reducer;
