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

const API_URL = process.env.API_URL;

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

	try {
		const accessToken = await getAccessToken();

		// 백엔드에서 파일 메타데이터(url, fileName) 조회 + 권한 체크
		const res = await fetch(`${API_URL}/api/forum/post/file/${uuid}`, {
			cache: 'no-store',
			headers: {
				...(accessToken ? { 'Authorization': `Bearer ${accessToken}` } : {})
			}
		});

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

		const json = await res.json();
		const fileUrl = json?.data?.url;
		const fileName = json?.data?.fileName;

		if (!fileUrl) {
			return new NextResponse(null, { status: 404 });
		}

		// 실제 파일 다운로드 (백엔드 서버에서)
		const fileRes = await fetch(`${API_URL}${fileUrl}`, {
			cache: 'no-store'
		});

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

		const contentType = fileRes.headers.get('content-type') || 'application/octet-stream';
		const buffer = await fileRes.arrayBuffer();

		const encodedFileName = encodeURIComponent(fileName || 'download');

		return new NextResponse(buffer, {
			status: 200,
			headers: {
				'Content-Type': contentType,
				'Content-Disposition': `attachment; filename*=UTF-8''${encodedFileName}`
			}
		});
	} catch {
		return new NextResponse(null, {
			status: 502
		});
	}
}
