import { NextRequest, NextResponse } from 'next/server';
import { fetchJson } from '@/lib/utils/server';

export async function GET(request: NextRequest)
{
	const { searchParams, origin } = request.nextUrl;
	const code = searchParams.get('code');
	const error = searchParams.get('error');

	if (error || !code) {
		return NextResponse.redirect(new URL('/studio/settings?error=cancelled', request.url));
	}

	const redirectUri = `${origin}/api/auth/youtube/callback`;

	const res = await fetchJson('/api/studio/youtube-connect', {
		method: 'POST',
		body: JSON.stringify({ code, redirectUri }),
		headers: { 'Content-Type': 'application/json' }
	});

	if (!res.success) {
		const msg = encodeURIComponent(res.message ?? '연결 실패');
		return NextResponse.redirect(new URL(`/studio/settings?error=${msg}`, request.url));
	}

	return NextResponse.redirect(new URL('/studio/settings?connected=true', request.url));
}