import jwt from 'jsonwebtoken';
import fs from 'fs';
import path from 'path';
import os from 'os';

const secretFilePath = path.join(
  os.homedir(),
  '.config',
  'api_jwt_keys.json'
);

// Load and parse keys JSON once at startup
const keyFileData = JSON.parse(fs.readFileSync(secretFilePath, 'utf-8'));

export function verifyToken(token) {
  if (!token) {
    return null;
  }

  try {
    const decoded = jwt.decode(token, { complete: true });
    if (!decoded?.header?.kid) {
      throw new Error('No kid in token header');
    }

    const kid = decoded.header.kid;
    const key = keyFileData.keys[kid];

    if (!key) {
      throw new Error(`Unknown kid: ${kid}`);
    }

    // Verify using the correct key and HS256 algo
    const payload = jwt.verify(token, key, { algorithms: ['HS256'] });
    return payload;

  } catch (error) {
    console.error('JWT verification failed:', error.message);
    return null;
  }
}
