'use client';

import { useAuthContext } from '@/contexts/authProvider';
import { useMemberContext } from '@/contexts/memberProvider';
import { getAccessToken } from '@/lib/utils/server';
import { fetchApi, decodeAccessToken } from '@/lib/utils/client';
import { MemberResponse } from '@/types/response/account/member';

export default function useAuth()
{
    const { isAuthenticated, isLoading, setIsAuthenticated } = useAuthContext();
	const { member, setMember } = useMemberContext();

	// 로그인
	const login = async (rememberMe: boolean) => {
		const accessToken = await getAccessToken();
		if (!accessToken) {
			return;
		}

		const tokenData = decodeAccessToken(accessToken);
		if (!tokenData) {
			return;
		}

		fetchApi<MemberResponse>('/api/auth/profile', {
			method: 'GET'
		}).then((res) => {
			setIsAuthenticated(true);
			setMember(res.data);

			localStorage.setItem('rememberMe', rememberMe.toString());
			localStorage.setItem("member", JSON.stringify(res.data));
			document.cookie = `member=${encodeURIComponent(JSON.stringify(res.data))}; path=/; max-age=${60 * 60 * 24 * 30}`;

			location.replace('/');
		}).catch(err => {
			console.error('로그인 처리 중 오류:', err);
		});
    };

	// 로그아웃
	const logout = async () => {
		fetchApi('/api/auth/logout', {
			method: 'POST'
		}).then(() => {
			setIsAuthenticated(false);
			setMember(null);

			localStorage.setItem('rememberMe', "false");
			localStorage.removeItem('member');
			document.cookie = 'member=; path=/; max-age=0';

			location.replace('/');
		}).catch(err => {
			console.error('로그인 처리 중 오류:', err);
		});
	};

	// 로그인 여부 확인
	const loginCheck = (): boolean => {
		if (!localStorage.getItem('member')) {
			if (confirm('로그인 후 이용 가능합니다.\n로그인하시겠습니까?')) {
				window.dispatchEvent(new CustomEvent('auth:unauthorized'));
			}
			return false;
		}
		return true;
	};

   	return { isAuthenticated, isLoading, login, logout, member, loginCheck };
}