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

router.get('/', (req, res) => {
  const db = getDb();
  const q = (req.query.q || '').trim();
  if (!q) return res.render('search-results', { query: q, results: { clients: [], engagements: [], tasks: [], diagrams: [], notes: [] } });
  const like = `%${q}%`;

  const clients = db.prepare(`SELECT id, name, industry, status FROM clients WHERE name LIKE ? OR industry LIKE ? OR contact_name LIKE ? OR contact_email LIKE ? OR notes LIKE ? LIMIT 20`).all(like, like, like, like, like);

  const engagements = db.prepare(`SELECT e.id, e.title, e.type, e.status, c.name as client_name FROM engagements e JOIN clients c ON c.id = e.client_id WHERE e.title LIKE ? OR e.description LIKE ? OR e.outcome LIKE ? LIMIT 20`).all(like, like, like);

  const tasks = db.prepare(`SELECT t.id, t.title, t.status, t.priority, e.title as engagement_title FROM tasks t JOIN engagements e ON e.id = t.engagement_id WHERE t.title LIKE ? OR t.description LIKE ? LIMIT 20`).all(like, like);

  const diagrams = db.prepare(`SELECT d.id, d.name, d.diagram_type, c.name as client_name FROM data_diagrams d JOIN clients c ON c.id = d.client_id WHERE d.name LIKE ? OR d.description LIKE ? LIMIT 20`).all(like, like);

  const notes = db.prepare(`SELECT n.id, n.content, n.created_at, c.name as client_name, c.id as client_id FROM client_notes n JOIN clients c ON c.id = n.client_id WHERE n.content LIKE ? LIMIT 20`).all(like);

  res.render('search-results', { query: q, results: { clients, engagements, tasks, diagrams, notes } });
});

module.exports = router;
