import { createRouter } from '../../create-router';
import { getVncPassword } from './vnc-config';
import * as sidecar from '@@/sidecar-registry';

export const desktopRouter = createRouter();

// The desktop UI asks for the password before it can open the WebSocket — and that WebSocket is what
// starts the VNC session. So this cannot wait for a session to exist: on a fresh install nothing has
// ever written the password, and answering "not configured" deadlocked the page permanently. Ask the
// sidecar to provision it instead; it owns the .vnc directory and the call is idempotent.
desktopRouter.get('/vnc-password', async (ctx) => {
  const user = ctx.get('user');

  const existing = await getVncPassword(user.email);
  if (existing) return ctx.json({ password: existing });

  if (!sidecar.isVncConnected()) {
    return ctx.json({ error: 'VNC sidecar is not connected' }, 503);
  }

  try {
    const password = await sidecar.ensureVncPassword(user.email);
    return ctx.json({ password });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Could not provision the VNC password';
    console.error('[desktop] VNC password provisioning failed:', message);
    return ctx.json({ error: message }, 500);
  }
});

desktopRouter.get('/vnc-status', async (ctx) => {
  const user = ctx.get('user');
  if (!sidecar.isVncConnected()) {
    return ctx.json({ connected: false, session: null });
  }
  const session = await sidecar.getVncStatus(user.email);
  return ctx.json({ connected: true, session });
});
