const { getDb } = require('../db');

function crmContextMiddleware(req, res, next) {
  const db = getDb();
  const qClientId = req.query.client_id || req.query.clientId;
  if (qClientId && req.session) {
    req.session.activeClientId = parseInt(qClientId, 10) || null;
  }

  const activeClientId = (req.session && req.session.activeClientId) || null;
  let activeClient = null;
  if (activeClientId) {
    activeClient = db.prepare('SELECT id, name, status, industry FROM clients WHERE id = ?').get(activeClientId);
    if (!activeClient) req.session.activeClientId = null;
  }

  const allClients = db.prepare('SELECT id, name, status FROM clients ORDER BY name').all();

  res.locals.activeClient = activeClient;
  res.locals.activeClientId = activeClient ? activeClient.id : null;
  res.locals.allClients = allClients;
  res.locals.clientQuery = (path) => {
    if (!activeClient) return path;
    const sep = path.includes('?') ? '&' : '?';
    return `${path}${sep}client_id=${activeClient.id}`;
  };

  next();
}

function getClientHubLinks(clientId) {
  const id = clientId;
  const q = `?client_id=${id}`;
  return [
    { href: `/clients/${id}`, icon: 'eye', label: 'Overzicht' },
    { href: `/engagements/new${q}`, icon: 'briefcase', label: 'Engagement' },
    { href: `/consulting${q}`, icon: 'clipboard-list', label: 'Framework' },
    { href: `/assess/${id}`, icon: 'file-search', label: 'Assessment' },
    { href: `/architecture/new/${id}`, icon: 'network', label: 'Design' },
    { href: `/architecture/designer${q}`, icon: 'pen-tool', label: 'Pro Designer' },
    { href: `/quality${q}`, icon: 'shield-check', label: 'Data Quality' },
    { href: `/racks${q}`, icon: 'server', label: 'Racks' },
    { href: `/networking${q}`, icon: 'share-2', label: 'Netwerk' },
    { href: `/time${q}`, icon: 'clock', label: 'Uren' },
    { href: `/invoices/new${q}`, icon: 'receipt', label: 'Factuur' },
    { href: `/email/compose${q}`, icon: 'mail', label: 'Email' }
  ];
}

module.exports = { crmContextMiddleware, getClientHubLinks };
