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

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

	const url = new URL('/charge/fail', request.url);
	url.searchParams.set('orderId', orderId);
	url.searchParams.set('errorCode', errorCode);
	url.searchParams.set('errorMessage', errorMessage);

	return NextResponse.redirect(url);
}

export async function POST(request: NextRequest) {
	const contentType = request.headers.get('content-type') || '';
	let orderId = '';
	let errorCode = '';
	let errorMessage = '';

	if (contentType.includes('application/x-www-form-urlencoded')) {
		const formData = await request.formData();
		orderId = (formData.get('orderId') as string) || '';
		errorCode = (formData.get('errorCode') as string) || (formData.get('code') as string) || '';
		errorMessage = (formData.get('errorMessage') as string) || (formData.get('message') as string) || '';
	} else {
		try {
			const json = await request.json();
			orderId = json.orderId || '';
			errorCode = json.errorCode || json.code || '';
			errorMessage = json.errorMessage || json.message || '';
		} catch {
			orderId = request.nextUrl.searchParams.get('orderId') || '';
		}
	}

	const url = new URL('/charge/fail', request.url);
	url.searchParams.set('orderId', orderId);
	url.searchParams.set('errorCode', errorCode);
	url.searchParams.set('errorMessage', errorMessage);

	return NextResponse.redirect(url);
}