const db  = require('../db/db');
const { emit, emitToClass } = require('../sse');

/* POST /api/live — teacher creates live session */
function create(req, res) {
  const { class_id } = req.body;
  const teacher = req.user;
  if (!class_id) return res.status(400).json({ error: 'class_id required' });

  const cls = teacher.role === 'admin'
    ? db.prepare('SELECT id, name FROM classes WHERE id=?').get(class_id)
    : db.prepare('SELECT id, name FROM classes WHERE id=? AND teacher_id=?').get(class_id, teacher.id);
  if (!cls) return res.status(403).json({ error: 'Forbidden' });

  // End any active session for this class
  db.prepare(`UPDATE live_sessions SET status='finished', ended_at=datetime('now')
              WHERE class_id=? AND status IN ('waiting','active')`).run(class_id);

  const { lastInsertRowid } = db.prepare(
    `INSERT INTO live_sessions (class_id, teacher_id) VALUES (?,?)`
  ).run(class_id, teacher.id);

  emitToClass(class_id, { type: 'live_started', liveId: lastInsertRowid, className: cls.name });

  res.json(db.prepare('SELECT * FROM live_sessions WHERE id=?').get(lastInsertRowid));
}

/* PUT /api/live/:id/question — teacher sets next question */
function setQuestion(req, res) {
  const liveId = Number(req.params.id);
  const { question_id } = req.body;
  const teacher = req.user;

  const live = db.prepare('SELECT * FROM live_sessions WHERE id=?').get(liveId);
  if (!live) return res.status(404).json({ error: 'Not found' });
  if (live.teacher_id !== teacher.id && teacher.role !== 'admin')
    return res.status(403).json({ error: 'Forbidden' });

  // Don't delete old answers — they're scoped per (session, user, question_id) so history is preserved
  db.prepare(`UPDATE live_sessions SET question_id=?, status='active', show_results=0 WHERE id=?`)
    .run(question_id, liveId);

  const q = db.prepare(
    `SELECT q.id, q.text, q.type, q.difficulty, t.name AS topic
     FROM questions q LEFT JOIN topics t ON t.id=q.topic_id WHERE q.id=?`
  ).get(question_id);
  const options = db.prepare(
    'SELECT id, text, order_index FROM options WHERE question_id=? ORDER BY order_index'
  ).all(question_id);

  emitToClass(live.class_id, { type: 'live_question', liveId, question: { ...q, options } });
  res.json({ ok: true, question: { ...q, options } });
}

/* POST /api/live/:id/answer — student submits answer */
function answer(req, res) {
  const liveId = Number(req.params.id);
  const { option_id, answer_text } = req.body;
  const userId = req.user.id;

  const live = db.prepare(`SELECT * FROM live_sessions WHERE id=? AND status='active'`).get(liveId);
  if (!live) return res.status(404).json({ error: 'Сессия не активна' });

  // Verify caller is a member of the class hosting this live session
  const isMember = db.prepare(
    'SELECT 1 FROM class_members WHERE class_id = ? AND user_id = ?'
  ).get(live.class_id, userId);
  if (!isMember) return res.status(403).json({ error: 'Forbidden' });

  if (!live.question_id) return res.status(400).json({ error: 'No active question' });

  const existing = db.prepare(
    'SELECT id FROM live_answers WHERE live_session_id=? AND user_id=? AND question_id=?'
  ).get(liveId, userId, live.question_id);
  if (existing) return res.status(409).json({ error: 'Уже отвечено' });

  let is_correct = null;
  if (option_id) {
    const opt = db.prepare(
      'SELECT is_correct FROM options WHERE id=? AND question_id=?'
    ).get(option_id, live.question_id);
    is_correct = opt ? opt.is_correct : 0;
  }

  // Atomic INSERT — race-safe via UNIQUE(session, user, question_id)
  try {
    db.prepare(
      `INSERT INTO live_answers (live_session_id, user_id, question_id, option_id, answer_text, is_correct)
       VALUES (?,?,?,?,?,?)`
    ).run(liveId, userId, live.question_id, option_id || null, answer_text || null, is_correct);
  } catch (e) {
    if (String(e.message).includes('UNIQUE')) return res.status(409).json({ error: 'Уже отвечено' });
    throw e;
  }

  const { c: count } = db.prepare(
    'SELECT COUNT(*) AS c FROM live_answers WHERE live_session_id=? AND question_id=?'
  ).get(liveId, live.question_id);
  emit(live.teacher_id, { type: 'live_answer_count', liveId, count });

  res.json({ ok: true, is_correct });
}

/* GET /api/live/:id/results — teacher reveals & gets results */
function results(req, res) {
  const liveId  = Number(req.params.id);
  const teacher = req.user;

  const live = db.prepare('SELECT * FROM live_sessions WHERE id=?').get(liveId);
  if (!live) return res.status(404).json({ error: 'Not found' });
  if (live.teacher_id !== teacher.id && teacher.role !== 'admin')
    return res.status(403).json({ error: 'Forbidden' });

  const question = db.prepare(
    'SELECT id, text, explanation FROM questions WHERE id=?'
  ).get(live.question_id);

  const options = db.prepare(`
    SELECT o.id, o.text, o.is_correct,
           COUNT(la.id) AS chosen_count
    FROM options o
    LEFT JOIN live_answers la ON la.option_id=o.id AND la.live_session_id=? AND la.question_id=?
    WHERE o.question_id=?
    GROUP BY o.id ORDER BY o.order_index
  `).all(liveId, live.question_id, live.question_id);

  const stats = db.prepare(
    `SELECT COUNT(*) AS total, SUM(is_correct) AS correct
     FROM live_answers WHERE live_session_id=? AND question_id=?`
  ).get(liveId, live.question_id);

  db.prepare('UPDATE live_sessions SET show_results=1 WHERE id=?').run(liveId);
  emitToClass(live.class_id, { type: 'live_results', liveId, question, options, stats });

  res.json({ question, options, stats });
}

/* DELETE /api/live/:id — teacher ends session */
function end(req, res) {
  const liveId  = Number(req.params.id);
  const teacher = req.user;

  const live = db.prepare('SELECT * FROM live_sessions WHERE id=?').get(liveId);
  if (!live) return res.status(404).json({ error: 'Not found' });
  if (live.teacher_id !== teacher.id && teacher.role !== 'admin')
    return res.status(403).json({ error: 'Forbidden' });

  db.prepare(`UPDATE live_sessions SET status='finished', ended_at=datetime('now') WHERE id=?`).run(liveId);
  emitToClass(live.class_id, { type: 'live_ended', liveId });
  res.json({ ok: true });
}

/* GET /api/live/class/:classId/active — student polls active session */
function getActive(req, res) {
  const classId = Number(req.params.classId);

  // Only class members (or teachers/admins) may poll
  if (!['teacher', 'admin'].includes(req.user.role)) {
    const isMember = db.prepare(
      'SELECT 1 FROM class_members WHERE class_id = ? AND user_id = ?'
    ).get(classId, req.user.id);
    if (!isMember) return res.status(403).json({ error: 'Forbidden' });
  }

  const live = db.prepare(`
    SELECT * FROM live_sessions WHERE class_id=? AND status IN ('waiting','active')
    ORDER BY id DESC LIMIT 1
  `).get(classId);
  if (!live) return res.json({ active: false });

  let question = null, options = null, myAnswer = null;
  if (live.question_id && live.status === 'active') {
    question  = db.prepare('SELECT id, text, type FROM questions WHERE id=?').get(live.question_id);
    options   = db.prepare(
      'SELECT id, text, order_index FROM options WHERE question_id=? ORDER BY order_index'
    ).all(live.question_id);
    myAnswer  = db.prepare(
      'SELECT option_id, is_correct FROM live_answers WHERE live_session_id=? AND user_id=? AND question_id=?'
    ).get(live.id, req.user.id, live.question_id);
  }

  res.json({ active: true, live, question, options, myAnswer, showResults: live.show_results });
}

/* GET /api/live/:id — get session info (teacher) */
function getSession(req, res) {
  const liveId  = Number(req.params.id);
  const teacher = req.user;
  const live    = db.prepare('SELECT * FROM live_sessions WHERE id=?').get(liveId);
  if (!live) return res.status(404).json({ error: 'Not found' });
  if (live.teacher_id !== teacher.id && teacher.role !== 'admin')
    return res.status(403).json({ error: 'Forbidden' });

  const answerCount = db.prepare(
    'SELECT COUNT(*) AS c FROM live_answers WHERE live_session_id=?'
  ).get(liveId).c;

  const memberCount = db.prepare(
    'SELECT COUNT(*) AS c FROM class_members WHERE class_id=?'
  ).get(live.class_id).c;

  res.json({ ...live, answerCount, memberCount });
}

module.exports = { create, setQuestion, answer, results, end, getActive, getSession };
