// The render core, separated from the HTTP wiring so the node test can call it directly.
import { Canvas } from 'skia-canvas';
import { drawGameImage, setAlphabet } from '../dist/gameimage.mjs';

/**
 * renderRequest rasterizes one export request — the JSON shape the backend sends:
 * { game, moves, alphabet, labels, dateLocale, hostname, scale? } — into a PNG buffer.
 * game/moves are the ui-model shapes (GameView / MoveRecord[]) the shared drawGameImage
 * consumes; alphabet is the per-variant (index, letter, value) table it scores tiles with.
 */
export async function renderRequest(payload) {
  const { game, moves, alphabet, labels, dateLocale, timeZone, hostname, scale } = payload;
  if (!game || !Array.isArray(moves)) throw Object.assign(new Error('bad payload'), { status: 400 });
  setAlphabet(game.variant, alphabet ?? []);
  const canvas = new Canvas(1, 1);
  drawGameImage(canvas, game, moves, {
    actionLabel: (a) => (labels && labels[a]) || a,
    hostname: hostname || '',
    dateLocale: dateLocale || undefined,
    timeZone: timeZone || undefined,
    scale: scale || 2,
  });
  return canvas.toBuffer('png');
}
