import jwt from 'jsonwebtoken';

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

/**
 * Generate a signed token for one-click unsubscribe links.
 * Token contains userId and email, valid for 90 days.
 */
export function generateUnsubscribeToken(userId: string, email: string): string {
    return jwt.sign({ userId, email }, JWT_SECRET, { expiresIn: '90d' });
}

/**
 * Verify an unsubscribe token.
 */
export function verifyUnsubscribeToken(token: string): { userId: string; email: string } | null {
    try {
        return jwt.verify(token, JWT_SECRET) as { userId: string; email: string };
    } catch {
        return null;
    }
}

/**
 * Generate full unsubscribe URLs for email footers.
 */
export function getUnsubscribeUrls(userId: string, email: string) {
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
    const token = generateUnsubscribeToken(userId, email);

    return {
        managePreferences: `${baseUrl}/dashboard/settings/email-preferences`,
        unsubscribeAll: `${baseUrl}/api/email/unsubscribe?token=${token}`,
        unsubscribeCategory: (category: string) =>
            `${baseUrl}/api/email/unsubscribe?token=${token}&category=${category}`,
        unsubscribeAlert: (alertId: string) =>
            `${baseUrl}/api/email/unsubscribe?token=${token}&alert=${alertId}`,
    };
}
