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

// 다날 successUrl 핸들러
// PC: POST (form body), 모바일: GET (query string)
export async function GET(request: NextRequest) {
	const params = request.nextUrl.searchParams;
	const orderId = params.get('orderId') || '';
	const transactionId = params.get('transactionId') || '';
	const method = params.get('method') || '';

	const url = new URL('/charge/success', request.url);
	url.searchParams.set('orderId', orderId);
	url.searchParams.set('transactionId', transactionId);
	url.searchParams.set('method', method);

	return NextResponse.redirect(url);
}

export async function POST(request: NextRequest) {
	// form-urlencoded 또는 JSON body 파싱
	const contentType = request.headers.get('content-type') || '';
	let orderId = '';
	let transactionId = '';
	let method = '';

	if (contentType.includes('application/x-www-form-urlencoded')) {
		const formData = await request.formData();
		orderId = (formData.get('orderId') as string) || '';
		transactionId = (formData.get('transactionId') as string) || '';
		method = (formData.get('method') as string) || '';
	} else {
		try {
			const json = await request.json();
			orderId = json.orderId || '';
			transactionId = json.transactionId || '';
			method = json.method || '';
		} catch {
			// fallback: query string
			orderId = request.nextUrl.searchParams.get('orderId') || '';
			transactionId = request.nextUrl.searchParams.get('transactionId') || '';
			method = request.nextUrl.searchParams.get('method') || '';
		}
	}

	const url = new URL('/charge/success', request.url);
	url.searchParams.set('orderId', orderId);
	url.searchParams.set('transactionId', transactionId);
	url.searchParams.set('method', method);

	return NextResponse.redirect(url);
}