const db = require('../db/db');

/* ── GET /api/search?q=...&type=...&limit=... ──────────────────────────── */
function search(req, res) {
  const q = (req.query.q || '').trim();
  if (!q || q.length < 2) return res.json({ results: [], total: 0 });

  const type  = req.query.type || 'all'; // all|lesson|course|file|question
  const limit = Math.min(Number(req.query.limit) || 20, 50);
  const uid   = req.user.id;
  const role  = req.user.role;
  const isTeacher = ['teacher', 'admin'].includes(role);
  const pattern = `%${q}%`;

  const results = [];

  /* ── Lessons ── */
  if (type === 'all' || type === 'lesson') {
    const pubFilter = isTeacher ? '' : 'AND l.is_published = 1 AND c.is_published = 1';
    const rows = db.prepare(`
      SELECT l.id, l.title, l.order_index, c.title AS course_title,
             c.id AS course_id, c.subject_slug, c.cover_emoji
      FROM lessons l
      JOIN courses c ON c.id = l.course_id
      WHERE l.title LIKE ? ${pubFilter}
      ORDER BY l.title LIMIT ?
    `).all(pattern, limit);
    for (const r of rows) {
      results.push({
        type: 'lesson',
        id: r.id,
        title: r.title,
        subtitle: r.course_title,
        extra: { courseId: r.course_id, subjectSlug: r.subject_slug, emoji: r.cover_emoji },
        url: `/lesson?id=${r.id}`,
      });
    }
  }

  /* ── Courses ── */
  if (type === 'all' || type === 'course') {
    const pubFilter = isTeacher ? '' : 'AND c.is_published = 1';
    const rows = db.prepare(`
      SELECT c.id, c.title, c.description, c.subject_slug, c.cover_emoji
      FROM courses c
      WHERE (c.title LIKE ? OR c.description LIKE ?) ${pubFilter}
      ORDER BY c.title LIMIT ?
    `).all(pattern, pattern, limit);
    for (const r of rows) {
      results.push({
        type: 'course',
        id: r.id,
        title: r.title,
        subtitle: r.description ? r.description.slice(0, 80) : '',
        extra: { subjectSlug: r.subject_slug, emoji: r.cover_emoji },
        url: `/course?id=${r.id}`,
      });
    }
  }

  /* ── Files (access-controlled) ── */
  if (type === 'all' || type === 'file') {
    const accessFilter = isTeacher
      ? '(f.uploaded_by = ? OR f.is_public = 1)'
      : `(
          f.is_public = 1
          OR EXISTS (SELECT 1 FROM file_access fa WHERE fa.file_id = f.id AND fa.type = 'user' AND fa.target_id = ?)
          OR EXISTS (SELECT 1 FROM file_access fa JOIN class_members cm ON cm.class_id = fa.target_id AND cm.user_id = ? WHERE fa.file_id = f.id AND fa.type = 'class')
        )`;
    const accessArgs = isTeacher ? [uid] : [uid, uid];

    const rows = db.prepare(`
      SELECT f.id, f.title, f.original_name, f.subject_slug, f.mimetype,
             u.name AS owner_name
      FROM files f
      JOIN users u ON u.id = f.uploaded_by
      WHERE (f.title LIKE ? OR f.original_name LIKE ?) AND ${accessFilter}
      ORDER BY f.title LIMIT ?
    `).all(pattern, pattern, ...accessArgs, limit);
    for (const r of rows) {
      results.push({
        type: 'file',
        id: r.id,
        title: r.title || r.original_name,
        subtitle: r.owner_name || '',
        extra: { subjectSlug: r.subject_slug, mimetype: r.mimetype },
        url: `/library`,
      });
    }
  }

  /* ── Questions ── */
  if (type === 'all' || type === 'question') {
    if (isTeacher) {
      const rows = db.prepare(`
        SELECT q.id, q.text, s.slug AS subject_slug, t.name AS topic_name
        FROM questions q
        LEFT JOIN topics t ON t.id = q.topic_id
        LEFT JOIN subjects s ON s.id = q.subject_id
        WHERE q.text LIKE ?
        ORDER BY q.id DESC LIMIT ?
      `).all(pattern, limit);
      for (const r of rows) {
        results.push({
          type: 'question',
          id: r.id,
          title: r.text.length > 100 ? r.text.slice(0, 100) + '…' : r.text,
          subtitle: r.topic_name || '',
          extra: { subjectSlug: r.subject_slug },
          url: `/theory`,
        });
      }
    }
  }

  res.json({ results: results.slice(0, limit), total: results.length });
}

module.exports = { search };
