import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { musicSectionService, MusicSection } from "@/services/musicSectionService";

interface MusicSectionState {
  sections: MusicSection[];
  isLoading: boolean;
  error: string | null;
  contentType: number;
}

const initialState: MusicSectionState = {
  sections: [],
  isLoading: false,
  error: null,
  contentType: 2,
};

export const fetchMusicSections = createAsyncThunk(
  "musicSection/fetch",
  async (contentType: number, { rejectWithValue }) => {
    try {
      const res = await musicSectionService.getSections(contentType);
      if (res.status !== 200) return rejectWithValue(res.message);
      return {
        sections: res.result.map(musicSectionService.mapSection),
        contentType,
      };
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Failed to load sections";
      return rejectWithValue(msg);
    }
  },
);

const musicSectionSlice = createSlice({
  name: "musicSection",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchMusicSections.pending, (state) => {
        state.isLoading = true;
        state.error = null;
        state.sections = [];
      })
      .addCase(fetchMusicSections.fulfilled, (state, action) => {
        state.isLoading = false;
        state.sections = action.payload.sections;
        state.contentType = action.payload.contentType;
      })
      .addCase(fetchMusicSections.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      });
  },
});

export default musicSectionSlice.reducer;
