'use strict';
const db = require('../../db/db');
const { emitToSession } = require('./_shared');

function simOpen(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: 'Нет доступа' });

  const { simId, title } = req.body;
  if (!simId || typeof simId !== 'string' || !/^[a-z0-9_-]{1,40}$/.test(simId))
    return res.status(400).json({ error: 'Неверный simId' });

  emitToSession(sessionId, { type: 'classroom_sim_open', sessionId, simId, title: (title || simId).slice(0, 80) });
  res.json({ ok: true });
}

function simState(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: 'Нет доступа' });

  const { state } = req.body;
  if (!state || typeof state !== 'object') return res.status(400).json({ error: 'Нет state' });
  const stateStr = JSON.stringify(state);
  if (stateStr.length > 64_000) return res.status(413).json({ error: 'State слишком большой' });

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

function simMode(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: 'Нет доступа' });

  const { mode } = req.body;
  if (mode !== 'demo' && mode !== 'free') return res.status(400).json({ error: 'mode must be demo|free' });

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

function simAnnotate(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: 'Нет доступа' });

  const { active } = req.body;
  emitToSession(sessionId, { type: 'classroom_sim_annotate', sessionId, active: !!active });
  res.json({ ok: true });
}

function simClose(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_sim_close', sessionId });
  res.json({ ok: true });
}

module.exports = { simOpen, simState, simMode, simAnnotate, simClose };
