import express from 'express';
import { Repository } from '../db/repository.js';
import { createNovncRouter, type NovncSessionAuthorizer } from './novnc-proxy.js';
import { canUserSeeTask } from './visibility.js';

/**
 * noVNC static hosting + the session authorizer closure, extracted verbatim
 * from createCoreServer (bridge/server.ts).
 */
export function mountNovncStatic(app: express.Application): void {
  // noVNC static files
  app.use('/novnc', createNovncRouter());
}

/**
 * CAPTCHA Pool は admin、Task Session はタスク visibility で認可。
 * novnc-proxy は Repository を直接知らずに済むよう、判定ロジックは
 * ここでクロージャに包んで渡す。
 */
export function buildNovncSessionAuthorizer(repo: Repository): NovncSessionAuthorizer {
  return async (session, user) => {
    if (session.kind === 'pool') {
      return user.role === 'admin';
    }
    if (session.kind === 'task' && session.taskId) {
      const taskIdNum = Number(session.taskId);
      if (!Number.isFinite(taskIdNum)) return false;
      const task = await repo.getLocalTask(taskIdNum);
      if (!task) return false;
      const spaceAccessible = task.spaceId ? repo.userCanViewSpace(task.spaceId, user) : false;
      return canUserSeeTask(user, task, spaceAccessible);
    }
    // legacy: kind 未設定 / taskId なし → 旧来の owner-or-admin
    const isOwner = session.userId === user.id;
    return isOwner || user.role === 'admin';
  };
}
