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


import { sageService } from '@/service/sageService';
import { BL, BLRequest, BLUpdateRequest } from '@/types/BL_Types';
import { StatusRequest, StatusResponse, TransformationResponse } from '@/types/sageTypes';
import { createAsyncThunk } from '@reduxjs/toolkit';


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


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


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



/**
 * create BL
 */
export const createBL = createAsyncThunk(
  'BL/createBL',
  async (data: BLRequest) => {
    try {
      return await sageService.createBL(data);
    } catch (err) {
      throw err;
    }
  }
);



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




/**
 * verified BLs
 */
export const selectBLAsync = createAsyncThunk<
  BL, 
  BL, 
  { state: any } 
>(
  "BL/selectBLAsync",
  async (items, { dispatch }) => {
    if (!items.lignes) {
      const updateItem = await dispatch(getBL(items.numero)).unwrap() as any
      return updateItem;
    }
    return items;
  }
);





/**
 * change bl to facture
 */
export const blToFacture = createAsyncThunk(
  'BL/blToFacture',
  async (numero: string):  Promise<TransformationResponse> => {
    try {
      return await sageService.blToFacture(numero);
    } catch (err) {
      throw err;
    }
  }
);


