import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { TRPCError } from "@trpc/server";
import { marketingPagesContainer } from "@/di/container";
import { MarketingPagesModule } from "@/di/module";
import { marketingPagesRouter } from "@/integrations/api/router";

describe("marketingPagesRouter", () => {
  beforeEach(() => {
    marketingPagesContainer.unbindAll();
    marketingPagesContainer.load(MarketingPagesModule);
  });

  afterEach(() => {
    marketingPagesContainer.unbindAll();
  });

  it("exposes pageBySlug + siteSettings procedures", () => {
    const names = Object.keys(marketingPagesRouter._def.procedures);
    expect(names).toContain("pageBySlug");
    expect(names).toContain("siteSettings");
  });

  it("pageBySlug returns the seeded About page", async () => {
    const caller = marketingPagesRouter.createCaller({});
    const result = await caller.pageBySlug({ slug: "about" });
    expect(result?.title).toBe("About");
  });

  it("siteSettings returns site name", async () => {
    const caller = marketingPagesRouter.createCaller({});
    const result = await caller.siteSettings({});
    expect(result.siteName).toBe("My App");
  });
});

describe("marketingPagesRouter (R26 error mapping)", () => {
  beforeEach(() => {
    marketingPagesContainer.unbindAll();
    marketingPagesContainer.load(MarketingPagesModule);
  });

  afterEach(() => {
    marketingPagesContainer.unbindAll();
  });

  it("translates zod parse failure → BAD_REQUEST on pageBySlug", async () => {
    const caller = marketingPagesRouter.createCaller({});
    try {
      await caller.pageBySlug({} as unknown as { slug: string });
      throw new Error("expected throw");
    } catch (e) {
      expect(e).toBeInstanceOf(TRPCError);
      expect((e as TRPCError).code).toBe("BAD_REQUEST");
    }
  });

  it("returns undefined (not NOT_FOUND) for missing slug since use case returns undefined", async () => {
    const caller = marketingPagesRouter.createCaller({});
    const result = await caller.pageBySlug({ slug: "does-not-exist" });
    expect(result).toBeUndefined();
  });
});
