import { getActiveHeadscaleCredentials } from '../db/queries';
import { createClient, type HeadscaleClient } from './client';

// Every domain route acts on the ACTIVE server — the one the owner selected in the servers section. That
// choice lives in Postgres (one row, enforced by a partial unique index), not in a request parameter, so
// no client can act on a server the owner isn't currently looking at by guessing an id.

/**
 * The client for the active server, or a ready-to-send 409 when there isn't one.
 *
 * 409 rather than 404: the route exists and the request was well-formed, the account just has no server
 * selected yet. The UI maps it to "pick a server", which is a different message from "that node is gone".
 */
export async function activeClient(userId: number): Promise<HeadscaleClient | Response> {
  const creds = await getActiveHeadscaleCredentials(userId);
  if (!creds) {
    return Response.json({ error: 'no active Headscale server', code: 'no_active_server' }, { status: 409 });
  }
  return createClient(creds);
}
