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 "./permanentlyClosePeriod";

describe("permanentlyClosePeriod", () => {
  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 OPEN status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAccountingPeriod]);

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

    expectErr(result, InvalidStatusTransitionError);
  });

  it("returns error when period is already PERMANENTLY_CLOSED", 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 CLOSED period to PERMANENTLY_CLOSED", async () => {
    const updatedPeriod = { ...closedPeriod, status: "PERMANENTLY_CLOSED" };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([closedPeriod], [updatedPeriod]);

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

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

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

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

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