import db from '../db.js';

export function generateSSRConfig(): string {
  const sub = db.prepare(
    'SELECT raw_config_ssr FROM subscriptions WHERE enabled = 1 AND raw_config_ssr IS NOT NULL ORDER BY id LIMIT 1'
  ).get() as any;

  if (!sub?.raw_config_ssr) {
    return '';
  }

  const staticNodes = db.prepare(
    'SELECT uri FROM static_nodes WHERE enabled = 1 ORDER BY sort_order, id'
  ).all() as any[];

  // Decode base64 content → URI list
  const decoded = Buffer.from(sub.raw_config_ssr.trim(), 'base64').toString();
  const lines = decoded.split(/\r?\n/).map((l: string) => l.trim()).filter(Boolean);

  // Append static node URIs
  for (const node of staticNodes) {
    if (node.uri) lines.push(node.uri);
  }

  return Buffer.from(lines.join('\n')).toString('base64');
}
