import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseCompany, baseSupplier, baseSupplierProfile } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getSupplierProfile";

describe("getSupplierProfile", () => {
  it("returns supplier profile when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseSupplierProfile);

    const result = await run(db, {
      companyId: baseCompany.id,
      supplierId: baseSupplier.id,
    });
    const { supplierProfile } = expectOk<{ supplierProfile: unknown }>(result as never);

    expect(supplierProfile).not.toBeNull();
    expect(supplierProfile).toMatchObject({ id: baseSupplierProfile.id });
  });

  it("returns default payment term reference when configured", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseSupplierProfile);

    const result = await run(db, {
      companyId: baseCompany.id,
      supplierId: baseSupplier.id,
    });
    const { supplierProfile } = expectOk<{
      supplierProfile: { defaultPurchasePaymentTermId: string };
    }>(result as never);

    expect(supplierProfile.defaultPurchasePaymentTermId).toBe("payment-term-1");
  });

  it("returns null when supplier profile does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, {
      companyId: baseCompany.id,
      supplierId: "nonexistent-supplier",
    });
    const { supplierProfile } = expectOk<{ supplierProfile: unknown }>(result as never);

    expect(supplierProfile).toBeNull();
  });
});
