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 } from "../testing/commandTestUtils";
import { run } from "./setSupplierDefaultPurchasePaymentTerm";

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

    const result = await run(
      db,
      {
        companyId: baseSupplierProfile.companyId,
        supplierId: baseSupplier.id,
        defaultPurchasePaymentTermId: basePaymentTerm.id,
      },
      commandCtx,
    );
    const value = expectOk<{ supplierProfile: typeof baseSupplierProfile }>(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" };
    spies.select
      .mockReturnValueOnce(baseSupplier)
      .mockReturnValueOnce({ role: "SUPPLIER" })
      .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,
    );
    const value = expectOk<{ supplierProfile: typeof updated }>(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 };
    spies.select
      .mockReturnValueOnce(baseSupplier)
      .mockReturnValueOnce({ role: "SUPPLIER" })
      .mockReturnValueOnce(baseSupplierProfile);
    spies.update.mockReturnValueOnce(cleared);

    const result = await run(
      db,
      {
        companyId: baseSupplierProfile.companyId,
        supplierId: baseSupplier.id,
        defaultPurchasePaymentTermId: null,
      },
      commandCtx,
    );
    const value = expectOk<{ supplierProfile: typeof cleared }>(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,
      ),
      SupplierNotFoundError,
    );
  });

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

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

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

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