import { describe, expect, it } from "vitest";
import {
  normalizeBrowserServiceConfig,
  normalizeRuntimePrepareConfig,
  normalizeTemplateLifecycleStep,
  normalizeTemplateStepInputs,
  normalizeTemplateInputs,
  parseModuleSpecifier,
} from "./runtime.mjs";

describe("config runtime helpers", () => {
  it("normalizes template inputs and steps", () => {
    expect(normalizeTemplateInputs(["foo.sql", "bar.sql"], "Service \"web\" database.template")).toEqual([
      "foo.sql",
      "bar.sql",
    ]);
    expect(
      normalizeRuntimePrepareConfig(
        {
          inputs: ["fixtures/users.json"],
          steps: [{ kind: "module", specifier: "./scripts/setup.mjs#run", inputs: ["fixtures/users.json"] }],
        },
        "web"
      )
    ).toEqual({
      inputs: ["fixtures/users.json"],
      steps: [
        {
          kind: "module",
          specifier: "./scripts/setup.mjs#run",
          cwd: null,
          inputs: ["fixtures/users.json"],
        },
      ],
    });
  });

  it("validates browser origins and module specifiers", () => {
    expect(normalizeBrowserServiceConfig({ origins: ["http://localhost:3000"] }, "web")).toEqual({
      origins: ["http://localhost:3000"],
    });
    expect(parseModuleSpecifier("./script.mjs#seed")).toEqual({
      modulePath: "./script.mjs",
      exportName: "seed",
    });
  });

  it("rejects malformed lifecycle steps and empty step inputs", () => {
    expect(() => normalizeTemplateLifecycleStep({ kind: "module" }, "runtime.prepare.steps[0]")).toThrow(
      /specifier must be a non-empty string/
    );
    expect(() => normalizeTemplateStepInputs([""], "runtime.prepare.steps[0]")).toThrow(
      /must be a non-empty string/
    );
  });
});
