import { NextRequest, NextResponse } from 'next/server';
import webPush from 'web-push';
import { getPushSubscriptionD1, getReminderSettingsD1 } from '@/lib/d1';
import { getSession } from '@/lib/session';

// Configure web-push
if (process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY && process.env.VAPID_PRIVATE_KEY) {
    webPush.setVapidDetails(
        process.env.VAPID_SUBJECT || 'mailto:example@yourdomain.org',
        process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY,
        process.env.VAPID_PRIVATE_KEY
    );
}

export async function POST(_request: NextRequest) {
    try {
        const session = await getSession();
        if (!session?.user) {
            console.error('Test Push: Unauthorized - No session');
            return NextResponse.json({ error: 'Unauthorized: No session found. Please refresh the page.' }, { status: 401 });
        }
        const userId = session.user.id;

        // 1. Get Subscription and Settings
        const [subscriptionRow, settings] = await Promise.all([
            getPushSubscriptionD1(userId),
            getReminderSettingsD1(userId)
        ]);

        if (!subscriptionRow) {
            console.error(`Test Push: No subscription found for user ${userId}`);
            return NextResponse.json({ error: 'No subscription found for your user. Please click Enable again.' }, { status: 404 });
        }

        const userTimezone = settings?.timezone || 'UTC (Default/Missing)';
        console.log(`Test Push: User ${userId} is in zone ${userTimezone}. Server time: ${new Date().toISOString()}`);

        // 3. Send Notification
        try {
            const payload = JSON.stringify({
                title: 'QuitTraq Test',
                body: `Success! Device linked. Server sees you in ${userTimezone}.`,
                tag: 'test-notification',
                url: '/'
            });

            const requestDetails = await webPush.generateRequestDetails(
                {
                    endpoint: subscriptionRow.endpoint,
                    keys: { p256dh: subscriptionRow.p256dh, auth: subscriptionRow.auth }
                },
                payload
            );

            const response = await fetch(requestDetails.endpoint, {
                method: 'POST',
                headers: requestDetails.headers as Record<string, string>,
                // @ts-expect-error - WebPush returns a Buffer
                body: requestDetails.body
            });

            if (!response.ok) {
                const text = await response.text();
                throw new Error(`Upstream error: ${response.status} ${text}`);
            }

            return NextResponse.json({ success: true, timezone: userTimezone });
        } catch (sendError) {
            console.error('Error sending test push:', sendError);
            return NextResponse.json({ error: `Failed to send to device: ${sendError}` }, { status: 500 });
        }

    } catch (error) {
        console.error('Test endpoint error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}
