/* eslint-disable import/order */
/* eslint-disable @typescript-eslint/consistent-type-imports */
import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { commandeState } from "./type";
import { changerStatutCommande, commandeToBL, commandeToFacture, createCommande, getCommande, getCommandes, selectCommandeAsync, updateCommande } from "./thunk";
import { Commande } from "@/types/commandeTypes";
import { StatusResponse, TransformationResponse } from "@/types/sageTypes";

const initialState: commandeState = {
    status: "idle",
    error: null,
    commandes: [],
    commandeSelected: null,
};

const commandeSlice = createSlice({
  name: "commande",
  initialState,
  reducers: {
    selectcommande: (state, action: PayloadAction<Commande>) => {
      state.commandeSelected = action.payload;
    }
  },
  extraReducers: (builder) => {


  /**
   * get all commandes
   */
    builder.addCase(getCommandes.fulfilled, (state, action) => {
      const data = action.payload;

      state.commandes = data;
      state.error = null;
      state.status = "succeeded";
    });

    builder.addCase(getCommandes.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(getCommandes.rejected, (state, action) => {
      state.status = "failed";
      state.error = action.error.message || "An error occurred";
    });

    /**
     * get commande by id
     */
    builder.addCase(getCommande.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(getCommande.fulfilled, (state, action) => {
      const data = action.payload as Commande;

      const idx = state.commandes.findIndex((n) => n.numero === data.numero);

      if (idx !== -1) {
        state.commandes[idx] = data;
      } else {
        state.commandes.push(data);
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(getCommande.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });

    /**
     * create commande
     */
    builder.addCase(createCommande.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(createCommande.fulfilled, (state) => {
      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(createCommande.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });

  /**
    * update commande
    */
    builder.addCase(updateCommande.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(updateCommande.fulfilled, (state) => {
      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(updateCommande.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });


  /**
   * verified commande
   */
    builder.addCase(selectCommandeAsync.fulfilled, (state, action) => {
      state.commandeSelected = {
        ...action.payload
      };
      const idx = state.commandes.findIndex(d => d.numero === action.payload.numero);
      if (idx !== -1) {
        state.commandes[idx] = state.commandeSelected;
      } else {
        state.commandes.push(state.commandeSelected);
      }
    });


    /**
     * devis to commande
     */
    builder.addCase(commandeToBL.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(commandeToBL.fulfilled, (state, action) => {
      const data = action.payload as TransformationResponse;
      const idx = state.commandes.findIndex((n) => n.numero === data.document_source);
      if (idx !== -1) {
        state.commandes.splice(idx, 1)
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(commandeToBL.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });


    /**
     * devis to facture
     */
    builder.addCase(commandeToFacture.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(commandeToFacture.fulfilled, (state, action) => {
      const data = action.payload as TransformationResponse;
      const idx = state.commandes.findIndex((n) => n.numero === data.document_source);
      if (idx !== -1) {
        state.commandes.splice(idx, 1)
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(commandeToFacture.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });


    /**
     * update commande status
     */
    builder.addCase(changerStatutCommande.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(changerStatutCommande.fulfilled, (state, action) => {
      const data = action.payload as StatusResponse;

      const idx = state.commandes.findIndex((n) => n.numero === data.document_id);
      
      if (idx !== -1) {
        const oldItem = state.commandes[idx];

        state.commandes[idx] = {
          ...oldItem,
          statut: data.statut_nouveau
        };
      }

      if (state.commandeSelected?.numero === data.document_id) {
        const oldItem = state.commandeSelected;

        state.commandeSelected= {
          ...oldItem,
          statut: data.statut_nouveau

        };
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(changerStatutCommande.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });

    

  },
});


export const { selectcommande } = commandeSlice.actions
export default commandeSlice.reducer;


