import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyScopeMismatchError,
  PartnerNotSupplierError,
  PaymentTermInactiveError,
  PaymentTermNotFoundError,
  SupplierNotFoundError,
} from "../lib/errors.generated";
import { basePaymentTerm, baseSupplier, baseSupplierProfile } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk, mockBPQueries } from "../testing/commandTestUtils";
import { run } from "./setSupplierDefaultPurchasePaymentTerm";

describe("setSupplierDefaultPurchasePaymentTerm", () => {
  it("creates a supplier profile when none exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select
      .mockReturnValueOnce(baseSupplier)
      .mockReturnValueOnce(basePaymentTerm)
      .mockReturnValueOnce(undefined);
    spies.insert.mockReturnValueOnce(baseSupplierProfile);

    const result = await run(
      db,
      {
        companyId: baseSupplierProfile.companyId,
        supplierId: baseSupplier.id,
        defaultPurchasePaymentTermId: basePaymentTerm.id,
      },
      commandCtx,
      bpQ,
    );
    const value = expectOk(result);

    expect(value.supplierProfile.id).toBe(baseSupplierProfile.id);
  });

  it("updates the default payment term on an existing supplier profile", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseSupplierProfile, defaultPurchasePaymentTermId: "payment-term-2" };
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select
      .mockReturnValueOnce(baseSupplier)
      .mockReturnValueOnce({ ...basePaymentTerm, id: "payment-term-2" })
      .mockReturnValueOnce(baseSupplierProfile);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(
      db,
      {
        companyId: baseSupplierProfile.companyId,
        supplierId: baseSupplier.id,
        defaultPurchasePaymentTermId: "payment-term-2",
      },
      commandCtx,
      bpQ,
    );
    const value = expectOk(result);

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

  it("clears the default payment term when explicit null is provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cleared = { ...baseSupplierProfile, defaultPurchasePaymentTermId: null };
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select.mockReturnValueOnce(baseSupplier).mockReturnValueOnce(baseSupplierProfile);
    spies.update.mockReturnValueOnce(cleared);

    const result = await run(
      db,
      {
        companyId: baseSupplierProfile.companyId,
        supplierId: baseSupplier.id,
        defaultPurchasePaymentTermId: null,
      },
      commandCtx,
      bpQ,
    );
    const value = expectOk(result);

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

  it("returns error when supplier does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);
    expectErr(
      await run(
        db,
        { companyId: baseSupplierProfile.companyId, supplierId: "missing" },
        commandCtx,
        mockBPQueries(),
      ),
      SupplierNotFoundError,
    );
  });

  it("returns error when partner is not a supplier", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const bpQ = mockBPQueries({ partnerRole: undefined });
    spies.select.mockReturnValueOnce(baseSupplier);
    expectErr(
      await run(
        db,
        { companyId: baseSupplierProfile.companyId, supplierId: baseSupplier.id },
        commandCtx,
        bpQ,
      ),
      PartnerNotSupplierError,
    );
  });

  it("returns error when payment term does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select.mockReturnValueOnce(baseSupplier).mockReturnValueOnce(undefined);
    expectErr(
      await run(
        db,
        {
          companyId: baseSupplierProfile.companyId,
          supplierId: baseSupplier.id,
          defaultPurchasePaymentTermId: "missing-term",
        },
        commandCtx,
        bpQ,
      ),
      PaymentTermNotFoundError,
    );
  });

  it("returns error when payment term is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select
      .mockReturnValueOnce(baseSupplier)
      .mockReturnValueOnce({ ...basePaymentTerm, status: "INACTIVE" });
    expectErr(
      await run(
        db,
        {
          companyId: baseSupplierProfile.companyId,
          supplierId: baseSupplier.id,
          defaultPurchasePaymentTermId: basePaymentTerm.id,
        },
        commandCtx,
        bpQ,
      ),
      PaymentTermInactiveError,
    );
  });

  it("returns error when payment term belongs to a different company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const bpQ = mockBPQueries({ partnerRole: { role: "SUPPLIER" } });
    spies.select
      .mockReturnValueOnce(baseSupplier)
      .mockReturnValueOnce({ ...basePaymentTerm, companyId: "company-2" });
    expectErr(
      await run(
        db,
        {
          companyId: baseSupplierProfile.companyId,
          supplierId: baseSupplier.id,
          defaultPurchasePaymentTermId: basePaymentTerm.id,
        },
        commandCtx,
        bpQ,
      ),
      CompanyScopeMismatchError,
    );
  });
});
