import { afterEach, describe, expect, it, vi } from "vitest";

const dbMocks = vi.hoisted(() => ({
  createCashOfferLead: vi.fn(),
  updateCashOfferLeadWebhook: vi.fn(),
}));

vi.mock("./db", () => dbMocks);

import { cashOfferLeadInputSchema, submitCashOfferLead } from "./leads";

afterEach(() => {
  vi.clearAllMocks();
});

describe("cash offer lead input", () => {
  it("normalizes a valid public request and applies secure defaults", () => {
    const input = cashOfferLeadInputSchema.parse({
      propertyAddress: "  100 Main Street, Austin, TX 78701  ",
      name: "  Taylor Seller  ",
      phone: "(512) 555-0199",
      email: "",
    });

    expect(input).toMatchObject({
      propertyAddress: "100 Main Street, Austin, TX 78701",
      name: "Taylor Seller",
      phone: "5125550199",
      leadSource: "cash-offer-form",
      consent: false,
    });
    expect(input.email).toBe("");
  });

  it("rejects incomplete contact data before it reaches storage", () => {
    expect(() =>
      cashOfferLeadInputSchema.parse({
        propertyAddress: "12",
        name: "A",
        phone: "123",
        email: "not-an-email",
      }),
    ).toThrow();
  });

  it("creates the lead before returning the deferred CRM state when no webhook is configured", async () => {
    const originalWebhookUrl = process.env.CRM_WEBHOOK_URL;
    delete process.env.CRM_WEBHOOK_URL;
    dbMocks.createCashOfferLead.mockResolvedValue({ id: 741 });

    try {
      const result = await submitCashOfferLead(
        cashOfferLeadInputSchema.parse({
          propertyAddress: "100 Main Street, Austin, TX 78701",
          name: "Taylor Seller",
          phone: "(512) 555-0199",
          leadSource: "homepage-offer-modal",
          consent: true,
        }),
      );

      expect(dbMocks.createCashOfferLead).toHaveBeenCalledWith({
        propertyAddress: "100 Main Street, Austin, TX 78701",
        name: "Taylor Seller",
        phone: "5125550199",
        email: undefined,
        timeline: undefined,
        leadSource: "homepage-offer-modal",
        consent: true,
        webhookStatus: "not_configured",
      });
      expect(dbMocks.updateCashOfferLeadWebhook).not.toHaveBeenCalled();
      expect(result).toEqual({ leadId: 741, webhookStatus: "not_configured" });
    } finally {
      if (originalWebhookUrl === undefined) delete process.env.CRM_WEBHOOK_URL;
      else process.env.CRM_WEBHOOK_URL = originalWebhookUrl;
    }
  });

  it("accepts only ten U.S. phone digits after normalization", () => {
    expect(cashOfferLeadInputSchema.parse({
      propertyAddress: "100 Main Street, Austin, TX 78701",
      name: "Taylor Seller",
      phone: "+1 (512) 555-0199",
    }).phone).toBe("5125550199");

    expect(() => cashOfferLeadInputSchema.parse({
      propertyAddress: "100 Main Street, Austin, TX 78701",
      name: "Taylor Seller",
      phone: "51255501990",
    })).toThrow();
  });
});
