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

const GUEST_EVENTS = new Set([
  'classroom_strokes', 'classroom_stroke_preview', 'classroom_stroke_deleted',
  'classroom_stroke_updated', 'classroom_page_added', 'classroom_page_changed',
  'classroom_template_changed', 'classroom_page_cleared', 'classroom_page_renamed',
  'classroom_page_duplicated', 'classroom_page_deleted', 'classroom_ended',
  'classroom_board_theme',
]);

function emitToSession(sessionId, data) {
  require('../../ws-server').broadcastToSession(sessionId, data, GUEST_EVENTS.has(data.type));
}

function hasAccess(session, userId, userRole) {
  if (userRole === 'admin') return true;
  if (session.teacher_id === userId) return true;
  if (session.class_id) {
    return !!db.prepare('SELECT 1 FROM class_members WHERE class_id=? AND user_id=?')
      .get(session.class_id, userId);
  } else {
    return !!db.prepare('SELECT 1 FROM classroom_invites WHERE session_id=? AND user_id=?')
      .get(session.id, userId);
  }
}

function canDraw(sessionId, userId, session) {
  if (session.teacher_id === userId) return true;
  return !!db.prepare(
    'SELECT 1 FROM classroom_draw_permissions WHERE session_id=? AND user_id=?'
  ).get(sessionId, userId);
}

module.exports = { GUEST_EVENTS, emitToSession, hasAccess, canDraw };
