import { Handler, Handlers } from "$fresh/server.ts";
import { SERVER_STATE } from "../../../state/serverState.ts";
import { downloadFile } from "../../../util/download.ts";

export const handler: Handlers = {
  async GET(_req, _ctx) {
    const gameVersions = JSON.parse(
      await Deno.readTextFile("./fabric/versions/game.json"),
    );
    const installerVersions = JSON.parse(
      await Deno.readTextFile("./fabric/versions/installer.json"),
    );
    const loaderVersions = JSON.parse(
      await Deno.readTextFile("./fabric/versions/loader.json"),
    );

    return new Response(JSON.stringify({
      gameVersions,
      installerVersions,
      loaderVersions,
    }));
  },
  async POST(req, _ctx) {
    try {
      const data = await req.formData();
      const game = data.get("game");
      const installer = data.get("installer");
      const loader = data.get("loader");

      await downloadFile(`https://meta.fabricmc.net/v2/versions/loader/${game}/${loader}/${installer}/server/jar`, './server/server.jar')
      
      SERVER_STATE.serverType = 'fabric';
      SERVER_STATE.startMCServer();

      const url = new URL(req.url);

      return Response.redirect(url.origin + "/setup/eula", 303);
    } catch (e) {
      console.log(e)
      return new Response("Something bad happened", { status: 500 });
    }
  },
};
