import { SignJWT, jwtVerify } from 'jose'
import { SITE_URL } from '@/lib/app-url'

/**
 * Signed, stateless links for the preference center and one-click unsubscribe
 * (2026-09-22). Bound to the recipient address (and user id when known);
 * no expiry — an old newsletter's unsubscribe link must keep working.
 */
export interface PreferenceToken { email: string; userId: string | null }

function key(): Uint8Array {
  const secret = process.env.AUTH_SECRET
  if (!secret || secret.length < 16) throw new Error('AUTH_SECRET must be set to a random string of at least 16 characters.')
  return new TextEncoder().encode(`${secret}:email-preferences`)
}

export async function createPreferenceToken(t: PreferenceToken): Promise<string> {
  return new SignJWT({ e: t.email.trim().toLowerCase(), u: t.userId, purpose: 'email-prefs' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().sign(key())
}

export async function verifyPreferenceToken(token: string): Promise<PreferenceToken | null> {
  try {
    const { payload } = await jwtVerify(token, key())
    if (payload.purpose !== 'email-prefs' || typeof payload.e !== 'string') return null
    return { email: payload.e, userId: typeof payload.u === 'string' ? payload.u : null }
  } catch {
    return null
  }
}

/**
 * Freight Broker Leads (2026-09-23): the personal join link in a lead campaign
 * email. Bound to the lead id and address; expires after 30 days so an old
 * list cannot be replayed for ever.
 */
export interface JoinToken { leadId: string; email: string }

export async function createJoinToken(t: JoinToken): Promise<string> {
  return new SignJWT({ l: t.leadId, e: t.email.trim().toLowerCase(), purpose: 'broker-join' }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime('30d').sign(key())
}

export async function verifyJoinToken(token: string): Promise<JoinToken | null> {
  try {
    const { payload } = await jwtVerify(token, key())
    if (payload.purpose !== 'broker-join' || typeof payload.l !== 'string' || typeof payload.e !== 'string') return null
    return { leadId: payload.l, email: payload.e }
  } catch {
    return null
  }
}

export function preferenceLinks(token: string, origin = SITE_URL) {
  return { unsubscribe: `${origin}/email/unsubscribe/${token}`, preferences: `${origin}/email/preferences/${token}` }
}
