import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  AccountingPeriodNotFoundError,
  InvalidStatusTransitionError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  neverOpenedPeriod,
  baseAccountingPeriod,
  closedPeriod,
  permanentlyClosedPeriod,
} from "../testing/fixtures";
import { run } from "./closePeriod";

describe("closePeriod", () => {
  it("returns error when accounting period does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { id: "non-existent" }, commandCtx));

    expectErr(result, AccountingPeriodNotFoundError);
  });

  it("returns error when period is in NEVER_OPENED status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([neverOpenedPeriod]);

    const result = await mock.withTx((trx) => run(trx, { id: neverOpenedPeriod.id }, commandCtx));

    expectErr(result, InvalidStatusTransitionError);
  });

  it("returns error when period is in CLOSED status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([closedPeriod]);

    const result = await mock.withTx((trx) => run(trx, { id: closedPeriod.id }, commandCtx));

    expectErr(result, InvalidStatusTransitionError);
  });

  it("returns error when period is in PERMANENTLY_CLOSED status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([permanentlyClosedPeriod]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: permanentlyClosedPeriod.id }, commandCtx),
    );

    expectErr(result, InvalidStatusTransitionError);
  });

  it("transitions OPEN period to CLOSED", async () => {
    const updatedPeriod = { ...baseAccountingPeriod, status: "CLOSED" };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAccountingPeriod], [updatedPeriod]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: baseAccountingPeriod.id }, commandCtx),
    );

    const value = expectOk(result);
    expect(value.accountingPeriod.status).toBe("CLOSED");
  });

  it("transitions OPEN period to CLOSED", async () => {
    const updatedPeriod = { ...baseAccountingPeriod, status: "CLOSED" };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAccountingPeriod], [updatedPeriod]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: baseAccountingPeriod.id }, commandCtx),
    );

    expectOk(result);
    expect(mock.updates.length).toBeGreaterThan(0);
  });
});
