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

function buildEndpoint(path?: string[]): string {
	const suffix = (path ?? []).join('/');
	return suffix ? `/api/feed/${suffix}` : '/api/feed';
}

async function forwardWithBody(request: NextRequest, endpoint: string, method: 'POST' | 'PUT'): Promise<ResultDto> {
	const contentType = request.headers.get('content-type') || '';

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

	if (contentType.includes('application/json')) {
		const text = await request.text();
		return await fetchJson(endpoint, {
			method,
			body: text || undefined,
			headers: { 'Content-Type': 'application/json' }
		});
	}

	return await fetchJson(endpoint, {
		method,
		body: await request.arrayBuffer(),
		headers: contentType ? { 'Content-Type': contentType } : undefined
	});
}

export async function GET(request: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
	const { path } = await params;
	const endpoint = buildEndpoint(path);
	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 = buildEndpoint(path);
	const res = await forwardWithBody(request, endpoint, 'POST');
	return NextResponse.json(res);
}

export async function DELETE(_: NextRequest, { params }: { params: Promise<{ path?: string[] }> }) {
	const { path } = await params;
	const endpoint = buildEndpoint(path);
	const res: ResultDto = await fetchJson(endpoint, { method: 'DELETE' });
	return NextResponse.json(res);
}