import { readFile } from "node:fs/promises";
import path from "node:path";

// At runtime (dist/render.js), __dirname is packages/email/dist/
const PKG_ROOT = path.join(__dirname, "..");
const TEMPLATES_ROOT = path.join(PKG_ROOT, "templates");
const CSS_PATH = path.join(PKG_ROOT, "email.css");

const BASE_URL = process.env.PUBLIC_URL ?? "https://sexy.pivoine.art";

export interface RenderOptions {
  url: string;
  [key: string]: unknown;
}

export async function renderTemplate(name: string, locals: RenderOptions): Promise<string> {
  // Dynamic import: @maizzle/framework v6 is ESM-only
  const { render } = await import("@maizzle/framework");

  const html = await readFile(path.join(TEMPLATES_ROOT, `${name}.html`), "utf8");

  const { html: rendered } = await render(html, {
    components: {
      root: TEMPLATES_ROOT,
      folders: ["layouts"],
    },
    // Override PostCSS `from` so @import "@maizzle/tailwindcss" resolves
    // from this package's node_modules (defu gives our value priority).
    postcss: {
      options: {
        from: CSS_PATH,
      },
    },
    locals: {
      cssPath: CSS_PATH, // layout uses {{ cssPath }} in <link href="{{ cssPath }}" inline>
      baseUrl: BASE_URL,
      ...locals,
    },
  });

  return rendered;
}
