import makeRequest from "@api/makeRequest";
import { parseAxiosError } from "@root/utils/parse-error";
import { createTicket as createTicketRequest } from "@frontend/kitui";
import type { CreateTicketResponse } from "@frontend/kitui";

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

type SendFileResponse = {
  message: string;
};

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

export const sendTicketMessage = async (
  ticketId: string,
  message: string
): Promise<[null, string?]> => {
  try {
    const sendTicketMessageResponse = await makeRequest<
      SendTicketMessageRequest,
      null
    >({
      method: "POST",
      url: `${API_URL}/send`,
      body: { ticket: ticketId, message: message, lang: "ru", files: [] },
      useToken: true,
    });

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

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

export const shownMessage = async (id: string): Promise<[null, string?]> => {
  try {
    const shownMessageResponse = await makeRequest<{ id: string }, null>({
      method: "POST",
      url: `${API_URL}/shown`,
      body: { id },
      useToken: true,
    });

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

    return [null, `Не удалось прочесть сообщение. ${error}`];
  }
};

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 (
  ticketNameField: string,
  ticketBodyField: string
): Promise<[CreateTicketResponse | null, string?]> => {
  try {
    const createTicketResponse = await createTicketRequest({
      url: `${API_URL}/create`,
      body: { Title: ticketNameField, Message: ticketBodyField, System: false },
    });

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

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