import { describe, expect, it } from "vitest";
import {
  contactBodySchema,
  contactSchema,
  isHoneypotTriggered,
  sanitizeHeaderValue,
} from "./contact";

describe("contact.ts utilities", () => {
  describe("sanitizeHeaderValue", () => {
    it("trims whitespace and removes newlines", () => {
      expect(sanitizeHeaderValue("  hello\r\nworld  ")).toBe("hello world");
    });

    it("slices to 200 chars", () => {
      const long = "a".repeat(300);
      const result = sanitizeHeaderValue(long);
      expect(result.length).toBe(200);
    });
  });

  describe("isHoneypotTriggered", () => {
    it("returns true if website is filled", () => {
      expect(isHoneypotTriggered({ website: "spam.com" })).toBe(true);
    });

    it("returns true if company is filled", () => {
      expect(isHoneypotTriggered({ company: "EvilCorp" })).toBe(true);
    });

    it("returns false for empty or whitespace", () => {
      expect(isHoneypotTriggered({ website: "   ", company: "" })).toBe(false);
      expect(isHoneypotTriggered({})).toBe(false);
    });
  });

  describe("contactSchema", () => {
    it("validates a minimal valid input", () => {
      const result = contactSchema.safeParse({
        name: "Jane Doe",
        email: "jane@example.com",
        message: "Hello there, this is a test message.",
      });
      expect(result.success).toBe(true);
      if (result.success) {
        expect(result.data.topic).toBe("general");
        expect(result.data.phone).toBe("");
      }
    });

    it("rejects short name", () => {
      const result = contactSchema.safeParse({
        name: "J",
        email: "j@example.com",
        message: "Valid message here.",
      });
      expect(result.success).toBe(false);
    });

    it("rejects invalid email", () => {
      const result = contactSchema.safeParse({
        name: "Jane",
        email: "not-an-email",
        message: "Valid message here.",
      });
      expect(result.success).toBe(false);
    });

    it("strips newlines from name", () => {
      const result = contactSchema.safeParse({
        name: "Jane\nDoe",
        email: "jane@example.com",
        message: "Hello there, this is long enough.",
      });
      expect(result.success).toBe(true);
      if (result.success) {
        expect(result.data.name).toBe("Jane Doe");
      }
    });

    it("rejects short message", () => {
      const result = contactSchema.safeParse({
        name: "Jane",
        email: "jane@example.com",
        message: "short",
      });
      expect(result.success).toBe(false);
    });
  });

  describe("contactBodySchema", () => {
    it("accepts honeypot fields", () => {
      const result = contactBodySchema.safeParse({
        name: "Jane",
        email: "jane@example.com",
        message: "A sufficiently long message for the body schema.",
        website: "",
        company: "",
      });
      expect(result.success).toBe(true);
    });
  });
});
