import { expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parse, resolveWrnImports } from "../src/index.ts";

test("configured import aliases resolve application client modules", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-import-alias-"));
  const app = join(root, "app");
  const page = join(app, "settings.wrn");
  const helper = join(app, "client", "storage.ts");
  const clientIndex = join(app, "client", "index.ts");
  mkdirSync(join(app, "client"), { recursive: true });
  writeFileSync(helper, "export function persist(value: unknown) { return value; }\n");
  writeFileSync(clientIndex, "export const storageReady = true;\n");

  try {
    const ast = parse(`import { persist } from "~/client/storage.ts"
page Settings { view { <button>Save</button> } }`);
    const [resolved] = resolveWrnImports(ast.structuredImports, page, {
      appRoot: root,
      mode: "explicit",
      aliases: { "~": "./app" },
    });
    expect(resolved?.diagnostic).toBeUndefined();
    expect(resolved?.resolved).toBe(helper);

    const directoryAst = parse(`import { storageReady } from "~client"
page ClientIndex { view { <p>Ready</p> } }`);
    const [directoryResolved] = resolveWrnImports(directoryAst.structuredImports, page, {
      appRoot: root,
      mode: "explicit",
      aliases: { "~client": "./app/client" },
    });
    expect(directoryResolved?.diagnostic).toBeUndefined();
    expect(directoryResolved?.resolved).toBe(clientIndex);
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});
