import { generateNestParams, handleError, handleSuccess } from '.';
import axios from '../lib/axios';
import { IKey } from '../system/type';

export const getKeys = async (params: Record<string, string | number>) => {
    return await axios({
        url: 'keys',
        params: generateNestParams(params),
        withCredentials: true,
        method: 'GET',
    });
};

export const createKey = async () => {
    try {
        const { data } = await axios({
            url: 'keys',
            withCredentials: true,
            method: 'POST',
        });

        handleSuccess(data);

        return data;
    } catch (error) {
        handleError(error);
    }
};

export const deleteKey = async (key: IKey) => {
    try {
        const { data } = await axios({
            url: 'keys/' + key.id,
            withCredentials: true,
            method: 'DELETE',
        });

        handleSuccess(data);

        return data;
    } catch (error) {
        handleError(error);
    }
};

export const deletesKey = async (keys: IKey[]) => {
    const ids = keys.reduce((prev, cur) => {
        prev.push(cur.id);
        return prev;
    }, [] as number[]);
    try {
        const { data } = await axios({
            url: 'keys/deletes',
            withCredentials: true,
            method: 'POST',
            data: {
                ids,
            },
        });

        handleSuccess(data);

        return data;
    } catch (error) {
        handleError(error);
    }
};
