import type { RequestHandler } from '@sveltejs/kit';
import { spawn } from 'node:child_process';

function runCommand(command: string, args: string[], timeoutMs = 8000): Promise<string> {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
    let out = '';
    let err = '';
    const timer = setTimeout(() => {
      child.kill('SIGKILL');
      reject(new Error('Timed out'));
    }, timeoutMs);
    child.stdout.on('data', (d) => { out += String(d); });
    child.stderr.on('data', (d) => { err += String(d); });
    child.on('error', (e) => { clearTimeout(timer); reject(e); });
    child.on('close', (code) => {
      clearTimeout(timer);
      if (code === 0 && out.trim().length > 0) resolve(out.trim());
      else reject(new Error(err || `Exited with code ${code}`));
    });
  });
}

/**
 * GET /api/steam/ticket
 * Returns a Steam session ticket as { ticket: string }.
 *
 * Implementation notes:
 * - In production Tauri, this should be replaced by a Tauri command using the Steamworks SDK.
 * - For now, this endpoint optionally runs a local helper binary specified by BL_STEAM_TICKET_CMD
 *   that prints the ticket to stdout.
 */
export const GET: RequestHandler = async () => {
  const helper = process.env.BL_STEAM_TICKET_CMD?.trim();
  if (!helper) {
    return new Response(
      JSON.stringify({ error: 'Steam ticket helper not configured', hint: 'Set BL_STEAM_TICKET_CMD to a helper binary that prints the Steam session ticket.' }),
      { status: 501, headers: { 'content-type': 'application/json' } }
    );
  }
  try {
    const [cmd, ...rest] = helper.split(/\s+/);
    const ticket = await runCommand(cmd, rest);
    return new Response(JSON.stringify({ ticket }), { headers: { 'content-type': 'application/json' } });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return new Response(JSON.stringify({ error: message }), { status: 500, headers: { 'content-type': 'application/json' } });
  }
};


