import axios from '@/utils/axios';
import { enqueueSnackbar } from 'notistack';
import { MemberListType } from './Types';
import { makeFormData } from '@/utils/jsonToFormData';

/**
 * Listing Member
 */
export const getMemberList = async ( page: number, keyword: string ): Promise<MemberListType[]> => {
    const response = await axios.get(`/claim-requests/list-member?page=${page}&keyword=${keyword}`)
        .then((res) =>{
            return res.data.data.member_list;
        })
        .catch((res) => {
            enqueueSnackbar("server error !", {
                variant: 'error',
            });

            return [];
        });

    return response;
};

/**
 * Add Claim Request
 */
export const addClaimRequest = async ( data: MemberListType[] ): Promise<boolean> => {
    // Mapping
    const formData = new FormData();

    data.map((row, index) => {
        formData.append(`member_id[${index}]`, row.id.toString());
        formData.append(`service_code[${index}]`, row.patien_type??'');

        if (row.file_kondisi != undefined) {
            row.file_kondisi.forEach((file, file_index) => {
                console.log(file);

                formData.append(`file_kondisi[member_${row.id}][${file_index}]`, file);
            });
        }

        if (row.file_diagnosa != undefined) {
            row.file_diagnosa.forEach((file, file_index) => {
                console.log(file);

                formData.append(`file_diagnosa[member_${row.id}][${file_index}]`, file);
            });
        }

        if (row.file_penunjang != undefined) {
            row.file_penunjang.forEach((file, file_index) => {
                console.log(file);

                formData.append(`file_penunjang[member_${row.id}][${file_index}]`, file);
            });
        }
    })

    // Axios
    const response = await axios.post(`/claim-requests`, formData)
        .then((res) =>{
            enqueueSnackbar("Berhasil membuat data !", {
                variant: 'success',
            });

            return true;
        })
        .catch((res) => {
            enqueueSnackbar("server error !", {
                variant: 'error',
            });

            return false;
        });

    return response;
};
