import { GetQuizDataResponse } from "@model/api/getQuizData";
import axios from "axios";

import type { AxiosError } from "axios";

let SESSIONS = "";

export const publicationMakeRequest = ({ url, body }: any) => {
    return axios(url, {
        data: body,
        headers: {
            "X-Sessionkey": SESSIONS,
            "Content-Type": "multipart/form-data",
        },
        method: "POST",
    });
};

export async function getData(quizId: string): Promise<{
    data: GetQuizDataResponse | null;
    isRecentlyCompleted: boolean;
    error?: string;
}> {
    try {
        const { data, headers } = await axios<GetQuizDataResponse>(
            `https://s.hbpn.link/answer/settings`,
            {
                method: "POST",
                headers: {
                    "X-Sessionkey": SESSIONS,
                    "Content-Type": "application/json",
                },
                data: {
                    quiz_id: quizId,
                    limit: 100,
                    page: 0,
                    need_config: true,
                },
            }
        );
        const sessions = JSON.parse(localStorage.getItem("sessions") || "{}");

        if (typeof sessions[quizId] === "number") {
            // unix время. Если меньше суток прошло - выводить ошибку, иначе пустить дальше
            if (Date.now() - sessions[quizId] < 86400000) {
                return { data, isRecentlyCompleted: true };
            }
        }

        SESSIONS = headers["x-sessionkey"];

        return { data, isRecentlyCompleted: false };
    } catch (nativeError) {
        const error = nativeError as AxiosError;

        return { data: null, isRecentlyCompleted: false, error: error.message };
    }
}

export function sendAnswer({ questionId, body, qid }: any) {
    const formData = new FormData();

    const answers = [
        {
            question_id: questionId,
            content: body, //тут массив с ответом
        },
    ];
    formData.append("answers", JSON.stringify(answers));
    formData.append("qid", qid);

    return publicationMakeRequest({
        url: `https://s.hbpn.link/answer/answer`,
        body: formData,
        method: "POST",
    });
}

//body ={file, filename}
export function sendFile({ questionId, body, qid }: any) {
    const formData = new FormData();

    const answers: any = [
        {
            question_id: questionId,
            content: "file:" + body.name,
        },
    ];

    formData.append("answers", JSON.stringify(answers));
    formData.append(body.name, body.file);
    formData.append("qid", qid);

    return publicationMakeRequest({
        url: `https://s.hbpn.link/answer/answer`,
        body: formData,
        method: "POST",
    });
}

//форма контактов
export function sendFC({ questionId, body, qid }: any) {
    const formData = new FormData();

    // const keysBody = Object.keys(body)
    // const content:any = {}
    // fields.forEach((key) => {
    //     if (keysBody.includes(key)) content[key] = body.key
    // })

    const answers = [
        {
            question_id: questionId,
            content: JSON.stringify(body),
            result: true,
            qid,
        },
    ];

    formData.append("answers", JSON.stringify(answers));
    formData.append("qid", qid);

    return publicationMakeRequest({
        url: `https://s.hbpn.link/answer/answer`,
        body: formData,
        method: "POST",
    });
}
