//인증 관련 api 연결

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

export const AuthInfo = async token => {
	try {
		const res = await Axios.get('/api/v1/admin/info', {
			headers: { Authorization: `Bearer ${token}` },
		});

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

export const AuthLogin = async params => {
	try {
		const res = await Axios.post('/api/v1/auth/login', params);

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

export const AuthRegist = async data => {
	try {
		const res = await Axios.post('/api/v1/auth/register', {
			email: data.userid,
			name: data.username,
			password: data.password,
		});

		return res.data;
	} catch (e) {
		if (e instanceof Error) {
			e.response.data.message.map(message => alert(message));
		}
	}
};

export const AuthLogout = async token => {
	try {
		const res = await Axios.post('/api/v1/auth/logout', {
			headers: { Authorization: `Bearer ${token}` },
		});
		return res;
	} catch (e) {
		if (e instanceof Error) {
			throw new Error('AuthLogout Error', e);
		}
	}
};

export const AuthEdit = async (data, token) => {
	try {
		const res = await Axios.patch(
			'/api/v1/admin/change-password',
			{
				password: data.password,
				new_password: data.newPassword,
			},
			{
				headers: { Authorization: `Bearer ${token}` },
			},
		);

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