import { ContractRendererService } from "../../contracts/contract-renderer.service";
import { CONTRACT_TEMPLATE_DEFAULTS } from "../../seed/data/contract-template-defaults";
import { ContractTemplatesService } from "./contract-templates.service";
import { ContractTemplatesRepository } from "./contract-templates.repository";
import {
  ContractTemplate,
  contractTemplateCodeFor,
} from "./entities/contract-template.entity";

function seededTemplate(code: string): ContractTemplate {
  const seed = CONTRACT_TEMPLATE_DEFAULTS.find((t) => t.code === code)!;
  return {
    id: "00000000-0000-0000-0000-000000000001",
    code: seed.code,
    name: seed.name,
    description: seed.description,
    documentTitle: seed.documentTitle,
    whereasClauses: seed.whereasClauses,
    articles: seed.articles.map((article, index) => ({ ...article, order: index + 1 })),
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: null,
  } as ContractTemplate;
}

describe("contractTemplateCodeFor", () => {
  it("maps every direction/freight pair to one of the six codes", () => {
    expect(contractTemplateCodeFor("IMPORT", "BULK")).toBe("IMPORT_BULK");
    expect(contractTemplateCodeFor("EXPORT", "CONTAINER")).toBe("EXPORT_CONTAINER");
    expect(contractTemplateCodeFor("DOMESTIC", "CONTAINER")).toBe("INTERCITY_CONTAINER");
    expect(contractTemplateCodeFor("DOMESTIC", "BULK")).toBe("INTERCITY_BULK");
    expect(contractTemplateCodeFor(null, null)).toBe("INTERCITY_CONTAINER");
  });
});

describe("ContractTemplatesService.preview", () => {
  const renderer = new ContractRendererService();
  renderer.onModuleInit();

  const repository = {
    findByCode: jest.fn((code: string) => Promise.resolve(seededTemplate(code))),
  } as unknown as ContractTemplatesRepository;

  const service = new ContractTemplatesService(repository, renderer);

  it.each(CONTRACT_TEMPLATE_DEFAULTS.map((t) => [t.code] as const))(
    "renders a complete mock preview for %s",
    async (code) => {
      const { html } = await service.preview(code);
      expect(html).toContain("Article 1");
      expect(html).toContain("Article 13");
      expect(html).toContain("Abyssinia Trading PLC");
      expect(html).toContain("Annex A — Commercial Schedule");
      // No unrendered handlebars placeholders may leak into the document.
      expect(html).not.toContain("{{");
      // Greenish theme applied.
      expect(html).toContain("#1b9e7a");
    },
  );

  it("interpolates {{contractYear}} inside seeded article bodies", async () => {
    const { html } = await service.preview("IMPORT_BULK");
    expect(html).toContain(`August 31, ${new Date().getFullYear()}`);
  });
});
