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

/**
 * GlitchTip/Sentry Tunnel API Route
 * 
 * This tunnels error reports from the client through our own API,
 * bypassing ad blockers that might block direct Sentry/GlitchTip requests.
 */
export async function POST(request: NextRequest) {
    const dsn = process.env.NEXT_PUBLIC_GLITCHTIP_DSN;

    console.log('[GlitchTip Tunnel] Received request');
    console.log('[GlitchTip Tunnel] DSN:', dsn ? dsn.substring(0, 40) + '...' : 'NOT SET');

    if (!dsn) {
        console.error('[GlitchTip Tunnel] No DSN configured');
        return NextResponse.json(
            { status: 'error', message: 'GlitchTip not configured' },
            { status: 503 }
        );
    }

    try {
        const body = await request.text();
        console.log('[GlitchTip Tunnel] Body length:', body.length);
        console.log('[GlitchTip Tunnel] Body preview:', body.substring(0, 200));

        // Parse the envelope header to get the DSN from the actual request
        // Sentry SDK sends: {"dsn":"...","sent_at":"..."}
        const envelopeHeader = body.split('\n')[0];
        let targetDsn = dsn;

        try {
            const headerData = JSON.parse(envelopeHeader);
            if (headerData.dsn) {
                targetDsn = headerData.dsn;
                console.log('[GlitchTip Tunnel] Using DSN from envelope:', targetDsn.substring(0, 40) + '...');
            }
        } catch {
            console.log('[GlitchTip Tunnel] Could not parse envelope header, using env DSN');
        }

        // Parse the DSN to extract components
        // DSN format: https://<key>@<host>/<project_id>
        const dsnUrl = new URL(targetDsn);
        const key = dsnUrl.username;
        const host = dsnUrl.host;
        const projectId = dsnUrl.pathname.replace('/', '');

        // GlitchTip uses the same API as Sentry
        const glitchtipUrl = `https://${host}/api/${projectId}/envelope/`;

        console.log('[GlitchTip Tunnel] Forwarding to:', glitchtipUrl);

        const response = await fetch(glitchtipUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-sentry-envelope',
                'X-Sentry-Auth': `Sentry sentry_version=7, sentry_client=sentry.javascript.nextjs, sentry_key=${key}`,
            },
            body: body,
        });

        const responseText = await response.text();
        console.log('[GlitchTip Tunnel] Response status:', response.status);
        console.log('[GlitchTip Tunnel] Response body:', responseText.substring(0, 200));

        if (!response.ok) {
            console.error('[GlitchTip Tunnel] Error response:', response.status, responseText);
            return NextResponse.json(
                { status: 'error', message: 'Failed to forward to GlitchTip', details: responseText },
                { status: response.status }
            );
        }

        console.log('[GlitchTip Tunnel] ✅ Successfully forwarded to GlitchTip');
        return NextResponse.json({ status: 'ok' });
    } catch (error: any) {
        console.error('[GlitchTip Tunnel] Exception:', error);
        return NextResponse.json(
            { status: 'error', message: error.message },
            { status: 500 }
        );
    }
}
