import { handlers } from "@/auth";
import { NextResponse } from "next/server";

const { GET: AuthGET, POST: AuthPOST } = handlers;

// Helper: Menyesuaikan NEXTAUTH_URL secara dinamis agar mendukung banyak domain (hmfupi.or.id dan hmf.my.id)
function ensureValidAuthUrl(req: any) {
    try {
        const host = req.headers.get('x-forwarded-host') || req.headers.get('host');
        if (host) {
            const proto = req.headers.get('x-forwarded-proto') || 'https';
            const origin = `${proto}://${host}`;
            process.env.AUTH_URL = origin;
            process.env.NEXTAUTH_URL = origin;
            // console.log(`[NextAuth Fix] Set auth origin to: ${origin}`);
        }
    } catch (e) {
        console.error("URL Fixer error:", e);
    }
}

export async function GET(req: any) {
    try {
        ensureValidAuthUrl(req);
        const response = await AuthGET(req);
        return response;
    } catch (e: any) {
        console.error("NextAuth GET Error:", e);
        return NextResponse.json({
            error_message: e.message,
            error_stack: e.stack,
            error_name: e.name,
            debug_auth_url: process.env.AUTH_URL,
            debug_nextauth_url: process.env.NEXTAUTH_URL,
            debug_req_url: req.url
        }, { status: 500 });
    }
}

export async function POST(req: any) {
    try {
        ensureValidAuthUrl(req);
        const response = await AuthPOST(req);
        return response;
    } catch (e: any) {
        console.error("NextAuth POST Error:", e);
        return NextResponse.json({
            error_message: e.message,
            error_stack: e.stack,
            error_name: e.name
        }, { status: 500 });
    }
}
