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


import { sageService } from '@/service/sageService';
import { Article, ArticleRequest, ArticleUpdateRequest, StockRequest, StockResponse } from '@/types/articleType';
import { createAsyncThunk } from '@reduxjs/toolkit';


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


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




/**
 * add article
 */
export const createArticle = createAsyncThunk(
  'article/createArticle',
  async (data: ArticleRequest): Promise<Article> => {
    try {
      return await sageService.createArticle(data);
    } catch (err) {
      throw err;
    }
  }
);



/**
 * update article
 */
export const updateArticle = createAsyncThunk(
  'article/updateArticle',
  async (
    { reference, data }: { reference: string; data: ArticleUpdateRequest }
  ): Promise<Article> => {
    try {
      return await sageService.updateArticle(reference, data);
    } catch (err) {
      throw err;
    }
  }
);



/**
 * add stock
 */
export const addStock = createAsyncThunk(
  'article/addStock',
  async (data: StockRequest) => {
    try {
      const res = await sageService.addStock(data);
      return {
        data: res,
        quantite: data.lignes[0].quantite
      }
    } catch (err) {
      throw err;
    }
  }
);
