import { NextRequest, NextResponse } from 'next/server';
import { LoginResponse } from '@/types/response/auth';

const API_URL = process.env.API_URL;

export async function POST(request: NextRequest)
{
	// Google redirect 모드는 form data로 credential을 전송
	const formData = await request.formData();
	const credential = formData.get('credential') as string;

	if (!credential) {
		const url = new URL('/login', request.url);
		url.searchParams.set('error', 'Google 인증 정보가 없습니다.');
		return NextResponse.redirect(url);
	}

	// 백엔드 google-login API 직접 호출
	const res = await fetch(`${API_URL}/api/auth/google-login`, {
		method: 'POST',
		headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
		body: JSON.stringify({ credential }),
		cache: 'no-store'
	});

	const json = await res.json();

	if (json.success && json.data) {
		const data = json.data as LoginResponse;
		const response = NextResponse.redirect(new URL('/login/google/complete', request.url));
		const cookieOptions = { httpOnly: true, path: '/' };
		response.cookies.set('accessToken', data.accessToken, cookieOptions);
		response.cookies.set('refreshToken', data.refreshToken, cookieOptions);
		return response;
	}

	// 실패 시 로그인 페이지로 리다이렉트
	const url = new URL('/login', request.url);
	url.searchParams.set('error', json.message || 'Google 로그인에 실패했습니다.');
	return NextResponse.redirect(url);
}