import { createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice";

export const provinceWarehouseArchive = createAsyncThunk(
  "PROVINCE_WAREHOUSE_ARCHIVE",
  async (d) => {
    const { data, status } = await axios.post("ware-house-archive/", d);
    return { data, status };
  }
);

export const provinceGetWarehouseArchive = createAsyncThunk(
  "PROVINCE_GET_WAREHOUSE_ARCHIVE",
  async (params, { dispatch }) => {
    try {
      dispatch(LOADING_START());
      const requestParams = {
        date1: params?.date1,
        date2: params?.date2,
        search: params?.search ?? "filter",
        value: params?.value ?? "",
        page: params?.page ?? 1,
        page_size: params?.page_size ?? 10,
      };

      if (params?.archive_type) {
        requestParams.archive_type = params.archive_type;
      }

      if (params?.owner_type) {
        requestParams.owner_type = params.owner_type;
      }

      const { data, status } = await axios.get("ware-house-archive/", {
        params: requestParams,
      });
      dispatch(LOADING_END());
      return { data, status };
    } catch (e) {
      dispatch(LOADING_END());
      return { error: e.response?.data?.result || "خطا در دریافت اطلاعات" };
    }
  }
);

export const provinceDeleteWarehouseArchive = createAsyncThunk(
  "PROVINCE_DELETE_WAREHOUSE_ARCHIVE",
  async ({ key }, { dispatch }) => {
    try {
      dispatch(LOADING_START());
      const endpoint = "ware-house-archive/0/";
      const { data, status } = await axios.delete(`${endpoint}?key=${key}`);
      dispatch(LOADING_END());
      return { data, status };
    } catch (e) {
      dispatch(LOADING_END());
      return { error: e.response?.data?.result || "خطا در حذف بایگانی" };
    }
  }
);
