import { NextRequest, NextResponse } from 'next/server';

const API_URL = process.env.API_URL;

export async function GET(_: NextRequest, { params }: { params: Promise<{ uuid: string }> })
{
	const { uuid } = await params;

	try {
		const res = await fetch(`${API_URL}/api/forum/post/link/${uuid}`, {
			cache: 'no-store',
			redirect: 'manual'
		});

		// 백엔드에서 리다이렉트 응답이 오면 그대로 전달
		if (res.status >= 300 && res.status < 400) {
			const location = res.headers.get('location');
			if (location) {
				return NextResponse.redirect(location);
			}
		}

		if (!res.ok) {
			return new NextResponse(null, {
				status: res.status
			});
		}

		// JSON 응답인 경우 (URL 정보 반환)
		const contentType = res.headers.get('content-type') || '';
		if (contentType.includes('application/json')) {
			const data = await res.json();
			if (data?.data?.url) {
				return NextResponse.redirect(data.data.url);
			}
		}

		return new NextResponse(null, {
			status: 404
		});
	} catch {
		return new NextResponse(null, {
			status: 502
		});
	}
}