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

// The router resolves controllers from blogContainer (a singleton).
// We reload the module between tests to get a fresh MockArticlesRepository.
describe("blogRouter", () => {
  beforeEach(() => {
    blogContainer.unbindAll();
    blogContainer.load(BlogModule);
  });

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

  it("exposes articleBySlug, listArticles, createArticle procedures", () => {
    const procedureNames = Object.keys(blogRouter._def.procedures);
    expect(procedureNames).toContain("articleBySlug");
    expect(procedureNames).toContain("listArticles");
    expect(procedureNames).toContain("createArticle");
  });

  it("listArticles returns empty array by default", async () => {
    const caller = blogRouter.createCaller({});
    const result = await caller.listArticles({});
    expect(result).toEqual([]);
  });

  it("createArticle then articleBySlug returns the article", async () => {
    const caller = blogRouter.createCaller({});

    const created = await caller.createArticle({
      title: "Router Test Article",
      content: null,
      authorId: "u1",
      slug: "router-test",
    });
    expect(created.slug).toBe("router-test");

    const fetched = await caller.articleBySlug({ slug: "router-test" });
    expect(fetched.id).toBe(created.id);
  });
});

describe("blogRouter error mapping", () => {
  beforeEach(() => {
    blogContainer.unbindAll();
    blogContainer.load(BlogModule);
  });

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

  it("translates ArticleNotFoundError → NOT_FOUND", async () => {
    const caller = blogRouter.createCaller({});
    try {
      await caller.articleBySlug({ slug: "missing" });
      throw new Error("expected throw");
    } catch (e) {
      expect(e).toBeInstanceOf(TRPCError);
      expect((e as TRPCError).code).toBe("NOT_FOUND");
    }
  });

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