import { describe, test, expect } from "bun:test";
import {
  type CWCompanySite,
  serializeCwSite,
} from "../../src/modules/cw-utils/sites/companySites";

function buildMockSite(overrides: Partial<CWCompanySite> = {}): CWCompanySite {
  return {
    id: 1,
    name: "Main Office",
    addressLine1: "123 Test St",
    city: "Austin",
    stateReference: { id: 1, identifier: "TX", name: "Texas" },
    zip: "78701",
    country: { id: 1, name: "United States" },
    phoneNumber: "512-555-0100",
    faxNumber: "512-555-0101",
    taxCodeId: 10,
    expenseReimbursement: 0,
    primaryAddressFlag: true,
    defaultShippingFlag: false,
    defaultBillingFlag: true,
    defaultMailingFlag: false,
    mobileGuid: "guid-123",
    calendar: null,
    timeZone: null,
    company: { id: 100, identifier: "TestCo", name: "Test Company" },
    _info: {},
    ...overrides,
  };
}

describe("serializeCwSite", () => {
  test("serializes a full site correctly", () => {
    const site = buildMockSite();
    const result = serializeCwSite(site);

    expect(result.id).toBe(1);
    expect(result.name).toBe("Main Office");
    expect(result.address.line1).toBe("123 Test St");
    expect(result.address.line2).toBeNull();
    expect(result.address.city).toBe("Austin");
    expect(result.address.state).toBe("Texas");
    expect(result.address.zip).toBe("78701");
    expect(result.address.country).toBe("United States");
    expect(result.phoneNumber).toBe("512-555-0100");
    expect(result.faxNumber).toBe("512-555-0101");
    expect(result.primaryAddressFlag).toBe(true);
    expect(result.defaultShippingFlag).toBe(false);
    expect(result.defaultBillingFlag).toBe(true);
    expect(result.defaultMailingFlag).toBe(false);
  });

  test("handles addressLine2 present", () => {
    const site = buildMockSite({ addressLine2: "Suite 200" });
    const result = serializeCwSite(site);
    expect(result.address.line2).toBe("Suite 200");
  });

  test("handles null stateReference", () => {
    const site = buildMockSite({ stateReference: null });
    const result = serializeCwSite(site);
    expect(result.address.state).toBeNull();
  });

  test("handles null country — defaults to United States", () => {
    const site = buildMockSite({ country: null });
    const result = serializeCwSite(site);
    expect(result.address.country).toBe("United States");
  });

  test("handles empty phoneNumber and faxNumber", () => {
    const site = buildMockSite({ phoneNumber: "", faxNumber: "" });
    const result = serializeCwSite(site);
    expect(result.phoneNumber).toBeNull();
    expect(result.faxNumber).toBeNull();
  });

  test("does not include internal fields", () => {
    const site = buildMockSite();
    const result = serializeCwSite(site);
    expect(result).not.toHaveProperty("_info");
    expect(result).not.toHaveProperty("mobileGuid");
    expect(result).not.toHaveProperty("company");
    expect(result).not.toHaveProperty("taxCodeId");
  });
});
