'use strict';
const db = require('../../db/db');
const { emitToUser, invalidateDrawCache } = require('../../ws-server');
const { getOnlineUserIds } = require('../../sse');
const { emitToSession, hasAccess } = require('./_shared');

function getParticipants(req, res) {
  const sessionId = Number(req.params.id);
  const session   = db.prepare('SELECT * FROM classroom_sessions WHERE id=?').get(sessionId);
  if (!session) return res.status(404).json({ error: 'Не найдено' });
  if (!hasAccess(session, req.user.id, req.user.role)) return res.status(403).json({ error: 'Нет доступа' });

  const participants = db.prepare(`
    SELECT a.user_id, u.name, a.joined_at FROM classroom_attendance a
    JOIN users u ON u.id = a.user_id
    WHERE a.session_id=? AND a.left_at IS NULL ORDER BY a.joined_at
  `).all(sessionId);
  res.json({ participants });
}

function getAttendance(req, res) {
  const sessionId = Number(req.params.id);
  const session   = db.prepare('SELECT * FROM classroom_sessions WHERE id=?').get(sessionId);
  if (!session) return res.status(404).json({ error: 'Не найдено' });
  if (session.teacher_id !== req.user.id && req.user.role !== 'admin')
    return res.status(403).json({ error: 'Нет доступа' });

  const attendance = db.prepare(`
    SELECT a.*, u.name AS user_name FROM classroom_attendance a
    JOIN users u ON u.id = a.user_id WHERE a.session_id=? ORDER BY a.joined_at
  `).all(sessionId);
  res.json({ attendance });
}

function getOnlineStudents(req, res) {
  const onlineIds = getOnlineUserIds();
  if (!onlineIds.length) return res.json({ students: [] });
  const placeholders = onlineIds.map(() => '?').join(',');
  const students = db.prepare(
    `SELECT id, name FROM users WHERE id IN (${placeholders}) AND role IN ('student','free_student') ORDER BY name`
  ).all(...onlineIds);
  res.json({ students });
}

function raiseHand(req, res) {
  const sessionId = Number(req.params.id);
  const session   = db.prepare(`SELECT * FROM classroom_sessions WHERE id=? AND status='active'`).get(sessionId);
  if (!session) return res.status(404).json({ error: 'Сессия не активна' });
  if (!hasAccess(session, req.user.id, req.user.role)) return res.status(403).json({ error: 'Нет доступа' });

  db.prepare('INSERT OR IGNORE INTO classroom_hands (session_id, user_id) VALUES (?,?)').run(sessionId, req.user.id);
  emitToSession(sessionId, { type: 'classroom_hand_raised', sessionId, userId: req.user.id, userName: req.user.name });
  res.json({ ok: true });
}

function lowerHand(req, res) {
  const sessionId = Number(req.params.id);
  const session   = db.prepare('SELECT * FROM classroom_sessions WHERE id=?').get(sessionId);
  if (!session) return res.status(404).json({ error: 'Не найдено' });
  if (!hasAccess(session, req.user.id, req.user.role)) return res.status(403).json({ error: 'Нет доступа' });

  db.prepare('DELETE FROM classroom_hands WHERE session_id=? AND user_id=?').run(sessionId, req.user.id);
  emitToSession(sessionId, { type: 'classroom_hand_lowered', sessionId, userId: req.user.id });
  res.json({ ok: true });
}

function getHands(req, res) {
  const sessionId = Number(req.params.id);
  const session   = db.prepare('SELECT * FROM classroom_sessions WHERE id=?').get(sessionId);
  if (!session) return res.status(404).json({ error: 'Не найдено' });
  if (!hasAccess(session, req.user.id, req.user.role)) return res.status(403).json({ error: 'Нет доступа' });

  const hands = db.prepare(`
    SELECT h.user_id AS userId, u.name AS userName FROM classroom_hands h
    JOIN users u ON u.id = h.user_id WHERE h.session_id=?
  `).all(sessionId);
  res.json({ hands });
}

function allowDraw(req, res) {
  const sessionId = Number(req.params.id);
  const targetId  = Number(req.params.userId);
  const session   = db.prepare(`SELECT * FROM classroom_sessions WHERE id=? AND status='active'`).get(sessionId);
  if (!session) return res.status(404).json({ error: 'Сессия не активна' });
  if (session.teacher_id !== req.user.id && req.user.role !== 'admin')
    return res.status(403).json({ error: 'Нет доступа' });

  db.prepare('INSERT OR IGNORE INTO classroom_draw_permissions (session_id, user_id) VALUES (?,?)').run(sessionId, targetId);
  invalidateDrawCache(sessionId, targetId);
  emitToUser(targetId, { type: 'classroom_draw_permitted', sessionId });
  res.json({ ok: true });
}

function revokeDraw(req, res) {
  const sessionId = Number(req.params.id);
  const targetId  = Number(req.params.userId);
  const session   = db.prepare(`SELECT * FROM classroom_sessions WHERE id=? AND status='active'`).get(sessionId);
  if (!session) return res.status(404).json({ error: 'Сессия не активна' });
  if (session.teacher_id !== req.user.id && req.user.role !== 'admin')
    return res.status(403).json({ error: 'Нет доступа' });

  db.prepare('DELETE FROM classroom_draw_permissions WHERE session_id=? AND user_id=?').run(sessionId, targetId);
  invalidateDrawCache(sessionId, targetId);
  emitToUser(targetId, { type: 'classroom_draw_revoked', sessionId });
  res.json({ ok: true });
}

function mutePeer(req, res) {
  const sessionId = Number(req.params.id);
  const { user_id } = req.body;
  if (!user_id) return res.status(400).json({ error: 'user_id required' });

  const session = db.prepare(`SELECT * FROM classroom_sessions WHERE id=? AND status='active'`).get(sessionId);
  if (!session) return res.status(404).json({ error: 'Сессия не активна' });
  if (session.teacher_id !== req.user.id && req.user.role !== 'admin')
    return res.status(403).json({ error: 'Нет доступа' });

  db.prepare('INSERT OR IGNORE INTO classroom_muted (session_id, user_id, muted_by) VALUES (?,?,?)').run(sessionId, user_id, req.user.id);
  emitToUser(user_id, { type: 'classroom_muted', sessionId, by: req.user.id });
  res.json({ ok: true });
}

function unmutePeer(req, res) {
  const sessionId = Number(req.params.id);
  const { user_id } = req.body;
  if (!user_id) return res.status(400).json({ error: 'user_id required' });

  const session = db.prepare(`SELECT * FROM classroom_sessions WHERE id=? AND status='active'`).get(sessionId);
  if (!session) return res.status(404).json({ error: 'Сессия не активна' });
  if (session.teacher_id !== req.user.id && req.user.role !== 'admin')
    return res.status(403).json({ error: 'Нет доступа' });

  db.prepare('DELETE FROM classroom_muted WHERE session_id=? AND user_id=?').run(sessionId, user_id);
  emitToUser(user_id, { type: 'classroom_unmuted', sessionId, by: req.user.id });
  res.json({ ok: true });
}

function screenStart(req, res) {
  const sessionId = Number(req.params.id);
  const session   = db.prepare(`SELECT * FROM classroom_sessions WHERE id=? AND status='active'`).get(sessionId);
  if (!session) return res.status(404).json({ error: 'Сессия не активна' });
  if (session.teacher_id !== req.user.id && req.user.role !== 'admin')
    return res.status(403).json({ error: 'Нет доступа' });

  emitToSession(sessionId, { type: 'classroom_screen_started', sessionId });
  res.json({ ok: true });
}

function screenStop(req, res) {
  const sessionId = Number(req.params.id);
  const session   = db.prepare(`SELECT * FROM classroom_sessions WHERE id=? AND status='active'`).get(sessionId);
  if (!session) return res.status(404).json({ error: 'Сессия не активна' });
  if (session.teacher_id !== req.user.id && req.user.role !== 'admin')
    return res.status(403).json({ error: 'Нет доступа' });

  emitToSession(sessionId, { type: 'classroom_screen_stopped', sessionId });
  res.json({ ok: true });
}

module.exports = {
  getParticipants, getAttendance, getOnlineStudents,
  raiseHand, lowerHand, getHands,
  allowDraw, revokeDraw, mutePeer, unmutePeer,
  screenStart, screenStop,
};
