import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  EmptyScheduleError,
  ImmutableCompanyScopeError,
  InvalidDiscountConfigurationError,
  InvalidInstallmentTotalError,
  InvalidScheduleLineError,
  PaymentTermNotFoundError,
} from "../lib/errors.generated";
import { basePaymentTerm, inactivePaymentTerm } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./updatePurchasePaymentTerm";

describe("updatePurchasePaymentTerm", () => {
  it("updates name and schedule lines on an active payment term", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...basePaymentTerm, name: "Net 45" };
    spies.select.mockReturnValueOnce(basePaymentTerm);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(
      db,
      {
        id: basePaymentTerm.id,
        name: "Net 45",
        scheduleLines: [{ kind: "NET_DAYS", days: 45 }],
      },
      commandCtx,
    );

    expect(expectOk(result).purchasePaymentTerm.name).toBe("Net 45");
  });

  it("updates an inactive payment term without reactivating it", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...inactivePaymentTerm, name: "Corrected Inactive Term" };
    spies.select.mockReturnValueOnce(inactivePaymentTerm);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(
      db,
      { id: inactivePaymentTerm.id, name: "Corrected Inactive Term" },
      commandCtx,
    );

    expect(expectOk(result).purchasePaymentTerm.status).toBe("INACTIVE");
  });

  it("preserves historical purchase-order snapshots after update", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);
    spies.update.mockReturnValueOnce(basePaymentTerm);

    await run(db, { id: basePaymentTerm.id, name: "Updated" }, commandCtx);

    const setCall = spies.set.mock.calls[0]?.[0] as Record<string, unknown>;
    expect(setCall).not.toHaveProperty("paymentTermSnapshot");
  });

  it("preserves historical purchase-bill snapshots after update", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);
    spies.update.mockReturnValueOnce(basePaymentTerm);

    await run(db, { id: basePaymentTerm.id, notes: "Updated notes" }, commandCtx);

    const setCall = spies.set.mock.calls[0]?.[0] as Record<string, unknown>;
    expect(setCall).not.toHaveProperty("supplierTaxIdentification");
  });

  it("returns error when payment term does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "missing-term" }, commandCtx);

    expectErr(result, PaymentTermNotFoundError);
  });

  it("returns error when updated schedule is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);

    const result = await run(
      db,
      {
        id: basePaymentTerm.id,
        scheduleLines: [{ kind: "INSTALLMENT", days: 30, percentage: 90 }],
      },
      commandCtx,
    );

    expectErr(result, InvalidInstallmentTotalError);
  });

  it("returns error when the updated schedule is empty", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);

    const result = await run(
      db,
      {
        id: basePaymentTerm.id,
        scheduleLines: [],
      },
      commandCtx,
    );

    expectErr(result, EmptyScheduleError);
  });

  it("returns error when an updated schedule line is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);

    const result = await run(
      db,
      {
        id: basePaymentTerm.id,
        scheduleLines: [{ kind: "INSTALLMENT", days: 30, percentage: -10 }],
      },
      commandCtx,
    );

    expectErr(result, InvalidScheduleLineError);
  });

  it("returns error when an updated discount configuration is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);

    const result = await run(
      db,
      {
        id: basePaymentTerm.id,
        scheduleLines: [{ kind: "NET_DAYS", days: 30, discountPercentage: 2 }],
      },
      commandCtx,
    );

    expectErr(result, InvalidDiscountConfigurationError);
  });

  it("returns error when company scope is changed", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);

    const result = await run(db, { id: basePaymentTerm.id, companyId: "company-2" }, commandCtx);

    expectErr(result, ImmutableCompanyScopeError);
  });
});
