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

import { sageService } from '@/service/sageService';
import { Facture, FactureRequest, FactureUpdateRequest, RelanceRequest, RelanceResponse } from '@/types/factureType';
import { StatusRequest, StatusResponse } from '@/types/sageTypes';
import { createAsyncThunk } from '@reduxjs/toolkit';


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


/**
 * get facture by id
 */
export const getFacture = createAsyncThunk(
  'facture/getfacture',
  async (id: string) => {
    try {
      const rep = await sageService.getFacture(id) as any
      return rep.data as Facture
    } catch (err) {
      throw err;
    }
  }
);




/**
 * valider facture
 */
export const validerFacture = createAsyncThunk(
  'facture/validerFacture',
  async (id: string) => {
    try {
      return await sageService.validerFacture(id)
    } catch (err) {
      throw err;
    }
  }
);




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


/**
 * relance facture
 */
export const relancerFacture = createAsyncThunk(
  'facture/relancerFacture',
  async (data: RelanceRequest): Promise<RelanceResponse> => {
    try {
      return await sageService.relancerFacture(data);
    } catch (err) {
      throw err;
    }
  }
);







/**
 * create Facture
 */
export const createFacture = createAsyncThunk(
  'facture/createFacture',
  async (data: FactureRequest) => {
    try {
      return await sageService.createFacture(data);
    } catch (err) {
      throw err;
    }
  }
);



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




/**
 * verified Factures
 */
export const selectFactureAsync = createAsyncThunk<
  Facture, 
  Facture, 
  { state: any } 
>(
  "facture/selectFactureAsync",
  async (items, { dispatch }) => {
    if (!items.lignes) {
      const updateItem = await dispatch(getFacture(items.numero)).unwrap() as any
      return updateItem;
    }
    return items;
  }
);
