/* eslint-disable import/no-unresolved */
/* eslint-disable import/order */


import { sageService } from '@/service/sageService';
import { Commande, CommandeRequest, CommandeResponse, CommandeUpdateRequest } from '@/types/commandeTypes';
import { StatusRequest, StatusResponse, TransformationResponse } from '@/types/sageTypes';
import { createAsyncThunk } from '@reduxjs/toolkit';


/**
 * get all commandes
 */
export const getCommandes = createAsyncThunk(
  'commande/getCommandes',
  async (): Promise<Commande[]> => {
    try {
      return await sageService.getCommandes();
    } catch (err) {
      throw err;
    }
  }
);


/**
 * get commande by id
 */
export const getCommande = createAsyncThunk(
  'commande/getCommande',
  async (id: string): Promise<Commande> => {
    try {
      return await sageService.getCommande(id);
    } catch (err) {
      throw err;
    }
  }
);



/**
 * changed statut commande
 */
export const changerStatutCommande = createAsyncThunk(
  'commande/changerStatutCommande',
  async (data: StatusRequest):  Promise<StatusResponse> => {
    try {
      return await sageService.changerStatut(10, data);
    } catch (err) {
      throw err;
    }
  }
);


/**
 * commande to facture
 */
export const commandeToFacture = createAsyncThunk(
  'commande/commandeToFacture',
  async (id: string): Promise<TransformationResponse> => {
    try {
      return await sageService.commandeToFacture(id);
    } catch (err) {
      throw err;
    }
  }
);


/**
 * commande to BL
 */
export const commandeToBL = createAsyncThunk(
  'commande/commandeToBL',
  async (id: string): Promise<TransformationResponse> => {
    try {
      return await sageService.commandeToBL(id);
    } catch (err) {
      throw err;
    }
  }
);




/**
 * create commande
 */
export const createCommande = createAsyncThunk(
  'commande/createCommande',
  async (data: CommandeRequest): Promise<CommandeResponse> => {
    try {
      return await sageService.createCommande(data);
    } catch (err) {
      throw err;
    }
  }
);



/**
 * update commande
 */
export const updateCommande = createAsyncThunk(
  'commande/updateCommande',
  async (
    { numero, data }: { numero: string; data: CommandeUpdateRequest }
  ) => {
    try {
      return await sageService.updateCommande(numero, data);
    } catch (err) {
      throw err;
    }
  }
);




/**
 * verified commandes
 */
export const selectCommandeAsync = createAsyncThunk<
  Commande, 
  Commande, 
  { state: any } 
>(
  "commande/selectCommandeAsync",
  async (devis, { dispatch }) => {
    if (!devis.lignes) {
      const updateItem = await dispatch(getCommande(devis.numero)).unwrap() as any
      return updateItem;
    }
    return devis;
  }
);