/**
 * Lightweight EncryptID JWT verification for the sync server.
 *
 * Verifies tokens by calling the EncryptID server's /api/session/verify endpoint.
 * No dependencies required — uses Node.js built-in fetch.
 */

const ENCRYPTID_SERVER_URL = process.env.ENCRYPTID_SERVER_URL || 'https://encryptid.jeffemmett.com';

/**
 * Verify an EncryptID JWT token by calling the EncryptID server.
 * @param {string} token - The JWT token to verify
 * @returns {Promise<object|null>} The claims if valid, null otherwise
 */
export async function verifyToken(token) {
  if (!token) return null;

  try {
    const res = await fetch(`${ENCRYPTID_SERVER_URL.replace(/\/$/, '')}/api/session/verify`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ token }),
      signal: AbortSignal.timeout(5000),
    });

    if (!res.ok) return null;

    const data = await res.json();
    if (data.valid) {
      return data.claims || {};
    }
    return null;
  } catch (error) {
    console.error('Token verification failed:', error.message);
    return null;
  }
}

/**
 * Extract token from a URL query string.
 * @param {string} url - The full URL or path with query string
 * @returns {string|null} The token or null
 */
export function extractTokenFromURL(url) {
  try {
    // parse handles both full URLs and just paths with query strings
    const searchParams = new URL(url, 'http://localhost').searchParams;
    return searchParams.get('token') || null;
  } catch {
    return null;
  }
}
