//운영서비스 관리 - 화이트 리스트 api 연결

import { Axios } from '../utils';

export const WhiteListData = async token => {
	try {
		const res = await Axios.get(`/api/v1/white-list/list`, {
			headers: { Authorization: `Bearer ${token}` },
		});

		return res.data.data.list;
	} catch (e) {
		if (e instanceof Error) {
			throw new Error('whiteList Error', e);
		}
	}
};

// 선택 삭제
export const WhiteListDelete = async (token, params) => {
	try {
		const res = await Axios.delete(`/api/v1/white-list`, {
			headers: { Authorization: `Bearer ${token}` },
			data: { list: params },
		});

		return res;
	} catch (e) {
		if (e instanceof Error) {
			throw new Error('WhiteListDelete', e);
		}
	}
};

// 선택 승인
export const WhiteListAllow = async (token, params) => {
	try {
		const res = await Axios.patch(
			`/api/v1/white-list`,
			{ list: params },
			{
				headers: { Authorization: `Bearer ${token}` },
			},
		);
		return res;
	} catch (e) {
		if (e instanceof Error) {
			throw new Error('WhiteListAllow', e);
		}
	}
};

// 화이트 리스트 등록 (단일)
export const WhiteListRegist = async (token, params) => {
	try {
		const res = await Axios.post(`/api/v1/white-list`, params, {
			headers: { Authorization: `Bearer ${token}` },
		});
		return res;
	} catch (e) {
		if (e instanceof Error) {
			throw new Error('WhiteListRegist', e);
		}
	}
};

// 화이트리스트 엑셀 업로더
export const WhiteListExelUpload = async (token, file) => {
	const exelFile = new FormData();
	exelFile.append('file', file);
	try {
		const res = await Axios.post(`/api/v1/white-list/excel-upload`, exelFile, {
			headers: {
				'Content-Type': 'multipart/form-data',
				Authorization: `Bearer ${token}`,
			},
		});

		return res;
	} catch (e) {
		if (e instanceof Error) {
			throw new Error('WhiteListExelUpload', e);

		}
	}
};

// 화이트 리스트 등록(복수) -> 등록하는 것임
export const WhiteListMultiRegsit = async (token, file) => {
	const exelFile = new FormData();
	exelFile.append('file', file);
	try {
		const res = await Axios.post(`/api/v1/white-list/multiPost`, exelFile, {
			headers: {
				'Content-Type': 'multipart/form-data',
				Authorization: `Bearer ${token}`,
			},
		});

		return res;
	} catch (e) {
		if (e instanceof Error) {
			throw new Error('WhiteListMultiRegsit', e);

		}
	}
};

// 엑셀 다운로드
export const WhiteListExport = async (token, fileName) => {
	try{
		await Axios.get(`/api/v1/white-list/excelDownLoad`, {
			headers: { Authorization: `Bearer ${token}` },
			responseType: 'blob',
		}).then(response => {
			const href = URL.createObjectURL(response.data);

			const link = document.createElement('a');
			const fileName = 'Caliverse_whitelist.xlsx';
			link.href = href;
			link.setAttribute('download', `${fileName}`);
			document.body.appendChild(link);
			link.click();
		
			document.body.removeChild(link);
			URL.revokeObjectURL(href);
		})

	}catch(e) {
		if(e instanceof Error) {
			throw new Error('WhiteListExport Error', e);
		}
	}
};
