import { NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET || process.env.NEXTAUTH_SECRET || 'fallback-secret';

/**
 * One-click unsubscribe endpoint (CAN-SPAM compliant).
 * No login required — uses a signed token in the URL.
 * 
 * GET /api/email/unsubscribe?token=xxx
 * GET /api/email/unsubscribe?token=xxx&category=job_alerts
 * GET /api/email/unsubscribe?token=xxx&alert=<savedSearchId>
 */
export async function GET(request: Request) {
    const { searchParams } = new URL(request.url);
    const token = searchParams.get('token');
    const category = searchParams.get('category');
    const alertId = searchParams.get('alert');

    if (!token) {
        return NextResponse.json({ error: 'Missing token' }, { status: 400 });
    }

    try {
        // Verify the token
        const decoded = jwt.verify(token, JWT_SECRET) as { userId: string; email: string };

        const user = await prisma.user.findUnique({
            where: { id: decoded.userId },
            select: { id: true, email: true, name: true }
        });

        if (!user) {
            return NextResponse.json({ error: 'User not found' }, { status: 404 });
        }

        // Case 1: Unsubscribe from a specific job alert
        if (alertId) {
            await prisma.savedSearch.updateMany({
                where: { id: alertId, user_id: user.id },
                data: { is_active: false }
            });

            return buildConfirmationPage(user.name || 'there', 'job alert', alertId);
        }

        // Case 2: Unsubscribe from a specific category
        if (category) {
            await prisma.notificationSetting.upsert({
                where: { user_id_category: { user_id: user.id, category } },
                create: { user_id: user.id, category, email: 'off', in_app: true, sms: false, push: false },
                update: { email: 'off' }
            });

            return buildConfirmationPage(user.name || 'there', category);
        }

        // Case 3: Unsubscribe from ALL
        await prisma.$transaction([
            prisma.emailPreference.upsert({
                where: { user_id: user.id },
                create: { user_id: user.id, unsubscribed_all: true },
                update: { unsubscribed_all: true }
            }),
            prisma.emailSuppression.upsert({
                where: { email: user.email },
                create: { email: user.email, reason: 'unsubscribe', is_permanent: false },
                update: { reason: 'unsubscribe', suppressed_at: new Date() }
            })
        ]);

        return buildConfirmationPage(user.name || 'there', 'all emails');

    } catch (error: any) {
        if (error.name === 'JsonWebTokenError' || error.name === 'TokenExpiredError') {
            return NextResponse.json({ error: 'Invalid or expired token' }, { status: 401 });
        }
        console.error('[Unsubscribe] Error:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}

/**
 * POST for List-Unsubscribe-Post header support (RFC 8058).
 */
export async function POST(request: Request) {
    const formData = await request.formData();
    const listUnsubscribe = formData.get('List-Unsubscribe');

    // Extract token from body or URL
    const url = new URL(request.url);
    const token = url.searchParams.get('token');

    if (!token) {
        return NextResponse.json({ error: 'Missing token' }, { status: 400 });
    }

    try {
        const decoded = jwt.verify(token, JWT_SECRET) as { userId: string; email: string };

        await prisma.$transaction([
            prisma.emailPreference.upsert({
                where: { user_id: decoded.userId },
                create: { user_id: decoded.userId, unsubscribed_all: true },
                update: { unsubscribed_all: true }
            }),
            prisma.emailSuppression.upsert({
                where: { email: decoded.email },
                create: { email: decoded.email, reason: 'unsubscribe', is_permanent: false },
                update: { reason: 'unsubscribe', suppressed_at: new Date() }
            })
        ]);

        return NextResponse.json({ success: true });
    } catch {
        return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
    }
}

/**
 * Builds an HTML confirmation page for unsubscribe actions.
 */
function buildConfirmationPage(name: string, type: string, alertId?: string) {
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

    const html = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Unsubscribed - Proten Job Board</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
               background: #f8fafc; min-height: 100vh; display: flex; align-items: center; 
               justify-content: center; padding: 20px; }
        .card { background: white; border-radius: 12px; box-shadow: 0 4px 24px rgba(0,0,0,0.08);
                padding: 48px; max-width: 480px; width: 100%; text-align: center; }
        .icon { font-size: 48px; margin-bottom: 16px; }
        h1 { color: #1e293b; font-size: 24px; margin-bottom: 12px; }
        p { color: #64748b; font-size: 16px; line-height: 1.6; margin-bottom: 24px; }
        .btn { display: inline-block; padding: 12px 24px; border-radius: 8px; text-decoration: none;
               font-weight: 600; font-size: 14px; transition: all 0.2s; }
        .btn-primary { background: #6366f1; color: white; }
        .btn-primary:hover { background: #4f46e5; }
        .btn-outline { border: 1px solid #e2e8f0; color: #64748b; margin-left: 8px; }
        .btn-outline:hover { background: #f1f5f9; }
        .footer { margin-top: 32px; font-size: 13px; color: #94a3b8; }
    </style>
</head>
<body>
    <div class="card">
        <div class="icon">✉️</div>
        <h1>You've been unsubscribed</h1>
        <p>Hi ${name}, you've been successfully unsubscribed from <strong>${type}</strong>.</p>
        <p>You'll still receive critical emails like interview confirmations and account security alerts.</p>
        <div>
            <a href="${baseUrl}/dashboard/settings/email-preferences" class="btn btn-primary">
                Manage All Preferences
            </a>
            <a href="${baseUrl}" class="btn btn-outline">Go to Homepage</a>
        </div>
        <div class="footer">
            <p>Changed your mind? Visit your <a href="${baseUrl}/dashboard/settings/email-preferences">email preferences</a> to resubscribe.</p>
        </div>
    </div>
</body>
</html>`;

    return new Response(html, {
        status: 200,
        headers: { 'Content-Type': 'text/html' }
    });
}
