import fsp from "node:fs/promises";
import { writeFile } from "nitropack/kit";
import { defineNitroPreset } from "nitropack/kit";
import { dirname, relative, resolve } from "pathe";
const zeabur = defineNitroPreset(
  {
    extends: "node",
    entry: "./runtime/zeabur",
    output: {
      dir: "{{ rootDir }}/.zeabur/output",
      serverDir: "{{ output.dir }}/functions/__nitro.func",
      publicDir: "{{ output.dir }}/static"
    },
    hooks: {
      async compiled(nitro) {
        const buildConfigPath = resolve(
          nitro.options.output.dir,
          "config.json"
        );
        const cfg = {
          containerized: false,
          routes: [{ src: ".*", dest: "/__nitro" }]
        };
        await writeFile(buildConfigPath, JSON.stringify(cfg, null, 2));
        for (const [key, value] of Object.entries(nitro.options.routeRules)) {
          if (!value.isr) {
            continue;
          }
          const funcPrefix = resolve(
            nitro.options.output.serverDir,
            ".." + key
          );
          await fsp.mkdir(dirname(funcPrefix), { recursive: true });
          await fsp.symlink(
            "./" + relative(dirname(funcPrefix), nitro.options.output.serverDir),
            funcPrefix + ".func",
            "junction"
          );
          await writeFile(
            funcPrefix + ".prerender-config.json",
            JSON.stringify({ type: "Prerender" })
          );
        }
      }
    }
  },
  {
    name: "zeabur",
    stdName: "zeabur",
    url: import.meta.url
  }
);
const zeaburStatic = defineNitroPreset(
  {
    extends: "static",
    output: {
      dir: "{{ rootDir }}/.zeabur/output",
      publicDir: "{{ output.dir }}/static"
    },
    commands: {
      preview: "npx serve {{ output.publicDir }}"
    }
  },
  {
    name: "zeabur-static",
    url: import.meta.url,
    static: true
  }
);
export default [zeabur, zeaburStatic];
