import axios from "../../../config/axios";
import { AddMessageTicketType, CreateTicketType } from "../types/TicketTypes";

export const getTickets = async (status: string) => {
  let query = ``;
  if (status) {
    query = `?status=${status}`;
  }
  const { data } = await axios.get(`/tickets${query}`);
  return data;
};

export const createTicket = async (params: CreateTicketType) => {
  const { data } = await axios.post(`/tickets`, params);
  return data;
};

export const getCategoriesTicket = async () => {
  const { data } = await axios.get(`/tickets/categories`);
  return data;
};

export const uploadSingle = async (
  params: FormData,
  callback?: (value: number) => void
) => {
  const { data } = await axios.post(`/uploader/single-file`, params, {
    onUploadProgress: (progressEvent: any) => {
      if (progressEvent.bytes) {
        if (callback) {
          callback(
            Math.round((progressEvent.loaded / progressEvent.total) * 100)
          );
        }
      }
    },
  });
  if (callback) {
    callback(0);
  }
  return data;
};

export const uploadMultiple = async (
  params: FormData,
  callback?: (value: number) => void
) => {
  const { data } = await axios.post(`/uploader/multi-file`, params, {
    onUploadProgress: (progressEvent: any) => {
      if (progressEvent.bytes) {
        if (callback) {
          callback(
            Math.round((progressEvent.loaded / progressEvent.total) * 100)
          );
        }
      }
    },
  });
  if (callback) {
    callback(0);
  }
  return data;
};

export const getMessages = async (id: string) => {
  const { data } = await axios.get(`/tickets/${id}/messages`);
  return data;
};

export const addMessageTicket = async (
  id: string,
  params: AddMessageTicketType
) => {
  const { data } = await axios.post(`/tickets/${id}/messages`, params);
  return data;
};

export const closeTicket = async (id: string) => {
  const { data } = await axios.post(`/tickets/${id}/close`);
  return data;
};
