import { NextRequest, NextResponse } from 'next/server';
import { ResultDto } from '@/types/response/common';
import { LoginResponse } from '@/types/response/auth';
import { fetchJson } from '@/lib/utils/server';

export async function GET(request: NextRequest, { params }: { params: Promise<{ path: string[] }> })
{
	const { path } = await params;
	const searchParams = request.nextUrl.searchParams.toString();
	const endpoint = `/api/auth/${path.join('/')}${searchParams ? `?${searchParams}` : ''}`;

	const res: ResultDto = await fetchJson(endpoint, {
		method: 'GET'
	});

	return NextResponse.json(res);
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ path: string[] }> })
{
	const { path } = await params;
	const endpoint = `/api/auth/${path.join('/')}`;
	const body = request.headers.get('content-type')?.includes('application/json') ? await request.json() : null;

	const res: ResultDto = await fetchJson(endpoint, {
		method: 'POST',
	    ...(body && { body: JSON.stringify(body) })
	});

	const response = NextResponse.json(res);

	// 로그인 또는 토큰 갱신 성공 시 쿠키 설정
	if ((path[0] === 'login' || path[0] === 'google-login' || path[0] === 'refresh-token') && res.success && res.data) {
		const data = res.data as LoginResponse;
		const cookieOptions = { httpOnly: true, path: '/' };
		response.cookies.set('accessToken', data.accessToken, cookieOptions);
		response.cookies.set('refreshToken', data.refreshToken, cookieOptions);
	}

	if (path[0] === 'logout' && res.success) {
		response.cookies.delete('accessToken');
		response.cookies.delete('refreshToken');
	}

	return response;
}