import { createTicket as createTicketRequest } from "@frontend/kitui";

import { makeRequest } from "@frontend/kitui";

import { parseAxiosError } from "@utils/parse-error";

import type {
  SendTicketMessageRequest,
  CreateTicketResponse,
} from "@frontend/kitui";

type SendFileResponse = {
  message: string;
};

const API_URL = `${process.env.REACT_APP_DOMAIN}/heruvym/v1.0.0`;



export const sendFile = async (
  ticketId: string,
  file: File,
): Promise<[SendFileResponse | null, string?]> => {
  try {
    const body = new FormData();

    body.append(file.name, file);
    body.append("ticket", ticketId);

    const sendResponse = await makeRequest<FormData, SendFileResponse>({
      method: "POST",
      url: `${API_URL}/sendFiles`,
      body,
    });

    return [sendResponse];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось отправить файл. ${error}`];
  }
};

export const createTicket = async (
  message: string,
  useToken: boolean,
  systemError: boolean
): Promise<[CreateTicketResponse | null, string?]> => {
  try {
    const createdTicket = await createTicketRequest({
      url: `${process.env.REACT_APP_DOMAIN}/heruvym/v1.0.0/create`,
      body: { Title: "Unauth title", Message: message, system: systemError },
      useToken,
    });

    return [createdTicket];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось создать тикет. ${error}`];
  }
};
