import { NextResponse } from 'next/server';
import { logVisit } from '@/lib/db';

const ANALYTICS_KEY = process.env.ANALYTICS_KEY || 'default-analytics-key';

export async function POST(req: Request) {
    try {
        const analyticsKey = req.headers.get('X-Analytics-Key');
        if (analyticsKey !== ANALYTICS_KEY) {
            return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 });
        }

        const body = await req.json();

        if (typeof body.path !== 'string' || typeof body.timestamp !== 'number') {
            return NextResponse.json({ success: false, error: 'Invalid input' }, { status: 400 });
        }

        const headers = req.headers;
        const forwarded = headers.get('x-forwarded-for');
        const ip = forwarded ? forwarded.split(',')[0].trim() : 'unknown';

        try {
            logVisit(ip, body.path);
        } catch (e) {
            console.error('Failed to log visit to SQLite', e);
        }

        const adminUrl = process.env.ADMIN_DASH_URL || 'http://admin_dash:3000/api/track';

        fetch(adminUrl, {
            method: 'POST',
            body: JSON.stringify({ path: body.path, timestamp: body.timestamp, ip }),
            headers: {
                'Content-Type': 'application/json',
                'X-Forwarded-For': ip,
            },
        }).catch(e => console.error('Relay failed', e));

        return NextResponse.json({ success: true });
    } catch {
        return NextResponse.json({ success: false, error: 'Bad request' }, { status: 400 });
    }
}
