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

export async function GET(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
	const { path } = await params;
	const endpoint = `/api/member/${path.join('/')}`;
	const url = new URL(request.url);
	const res: ResultDto = await fetchJson(`${endpoint}${url.search}`, { method: 'GET' });
	return NextResponse.json(res);
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
	const { path } = await params;
	const endpoint = `/api/member/${path.join('/')}`;
	const contentType = request.headers.get('content-type') || '';

	if (contentType.includes('multipart/form-data')) {
		const form = await request.formData();
		const res: ResultDto = await fetchJson(endpoint, { method: 'POST', body: form });
		return NextResponse.json(res);
	}

	// JSON 이거나 기타 Content-Type: 원본 바이트 그대로 전달 (parse → stringify 사이클에서 body 유실 방지)
	const raw = await request.arrayBuffer();

	if (raw.byteLength > 0) {
		const res: ResultDto = await fetchJson(endpoint, {
			method: 'POST',
			body: raw,
			headers: contentType ? { 'Content-Type': contentType } : undefined
		});
		return NextResponse.json(res);
	}

	const res: ResultDto = await fetchJson(endpoint, { method: 'POST' });
	return NextResponse.json(res);
}