import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { encodeJson, type DueScheduleLine, type PaymentTermScheduleLineInput } from "../lib/domain";
import { InvalidPaymentTermDefinitionError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import {
  basePaymentTerm,
  installmentScheduleLines,
  endOfMonthScheduleLines,
} from "../testing/fixtures";
import { run } from "./calculateInvoiceDueSchedule";

const invoiceDate = new Date("2024-02-15T00:00:00.000Z");

describe("calculateInvoiceDueSchedule", () => {
  it("calculates net-day due schedule", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePaymentTerm]);

    const result = await run(mock.db, {
      paymentTermId: basePaymentTerm.id,
      invoiceDate,
      invoiceAmount: 1000,
    });
    const { dueSchedule } = expectOk<{ dueSchedule: DueScheduleLine[] }>(result as never);

    expect(dueSchedule).toHaveLength(1);
    expect(dueSchedule[0]).toMatchObject({
      amount: 1000,
      dueDate: new Date("2024-03-16T00:00:00.000Z"),
    });
  });

  it("calculates installment due schedule", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const installmentTerm = {
      ...basePaymentTerm,
      id: "payment-term-installment",
      scheduleLines: encodeJson(installmentScheduleLines),
    };
    mock.enqueueResults([installmentTerm]);

    const result = await run(mock.db, {
      paymentTermId: installmentTerm.id,
      invoiceDate,
      invoiceAmount: 1000,
    });
    const { dueSchedule } = expectOk<{ dueSchedule: DueScheduleLine[] }>(result as never);

    expect(dueSchedule).toHaveLength(2);
    expect(dueSchedule[0]).toMatchObject({
      amount: 500,
      dueDate: new Date("2024-03-01T00:00:00.000Z"),
    });
    expect(dueSchedule[1]).toMatchObject({
      amount: 500,
      dueDate: new Date("2024-03-16T00:00:00.000Z"),
    });
  });

  it("calculates end-of-month due schedule", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const eomTerm = {
      ...basePaymentTerm,
      id: "payment-term-eom",
      scheduleLines: encodeJson(endOfMonthScheduleLines),
    };
    mock.enqueueResults([eomTerm]);

    const result = await run(mock.db, {
      paymentTermId: eomTerm.id,
      invoiceDate,
      invoiceAmount: 500,
    });
    const { dueSchedule } = expectOk<{ dueSchedule: DueScheduleLine[] }>(result as never);

    expect(dueSchedule).toHaveLength(1);
    // End of February 2024 (leap year) → Feb 29
    expect(dueSchedule[0]).toMatchObject({
      amount: 500,
      dueDate: new Date("2024-02-29T00:00:00.000Z"),
    });
  });

  it("throws when payment term definition is invalid", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const invalidLines: PaymentTermScheduleLineInput[] = [
      { kind: "INSTALLMENT", days: 15, percentage: 40 },
      { kind: "INSTALLMENT", days: 30, percentage: 40 },
    ];
    const invalidTerm = {
      ...basePaymentTerm,
      id: "payment-term-invalid",
      scheduleLines: encodeJson(invalidLines),
    };
    mock.enqueueResults([invalidTerm]);

    const result = await run(mock.db, {
      paymentTermId: invalidTerm.id,
      invoiceDate,
      invoiceAmount: 1000,
    });

    expectErr(result as never, InvalidPaymentTermDefinitionError);
  });
});
