import { makeRequest } from "@frontend/kitui";
import { CreateQuestionRequest } from "model/question/create";
import { RawQuestion } from "model/question/question";
import { GetQuestionListRequest, GetQuestionListResponse } from "@model/question/getList";
import { EditQuestionRequest, EditQuestionResponse } from "@model/question/edit";
import { DeleteQuestionRequest, DeleteQuestionResponse } from "@model/question/delete";
import { CopyQuestionRequest, CopyQuestionResponse } from "@model/question/copy";


const baseUrl = process.env.NODE_ENV === "production" ? "/squiz" : "https://squiz.pena.digital/squiz";

function createQuestion(body: CreateQuestionRequest) {
    return makeRequest<CreateQuestionRequest, RawQuestion>({
        url: `${baseUrl}/question/create`,
        body,
        method: "POST",
    });
}

async function getQuestionList(body?: Partial<GetQuestionListRequest>) {
    if (!body?.quiz_id) return null;

    const response = await makeRequest<GetQuestionListRequest, GetQuestionListResponse>({
        url: `${baseUrl}/question/getList`,
        body: { ...defaultGetQuestionListBody, ...body },
        method: "POST",
    });

    return response.items;
}

function editQuestion(body: EditQuestionRequest, signal?: AbortSignal) {
    console.log("`${baseUrl}/question/edit` start")
    return makeRequest<EditQuestionRequest, EditQuestionResponse>({
        url: `${baseUrl}/question/edit`,
        body,
        method: "PATCH",
        signal,
    });
}

function copyQuestion(questionId: number, quizId: number) {
    return makeRequest<CopyQuestionRequest, CopyQuestionResponse>({
        url: `${baseUrl}/question/copy`,
        body: { id: questionId, quiz_id: quizId },
        method: "POST",
    });
}

function deleteQuestion(id: number) {
    return makeRequest<DeleteQuestionRequest, DeleteQuestionResponse>({
        url: `${baseUrl}/question/delete`,
        body: { id },
        method: "DELETE",
    });
}

export const questionApi = {
    create: createQuestion,
    getList: getQuestionList,
    edit: editQuestion,
    copy: copyQuestion,
    delete: deleteQuestion,
};


const defaultGetQuestionListBody: GetQuestionListRequest = {
    "limit": 100,
    "offset": 0,
    "type": "",
};
