import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  StockAdjustmentNotFoundError,
  InvalidStatusError,
  ItemNotFoundError,
} from "../lib/errors.generated";
import { mockItemManagementQueries } from "../testing/commandTestUtils";
import {
  baseActiveItem,
  baseDraftAdjustment,
  baseSubmittedAdjustment,
  correctionIncreaseLine,
} from "../testing/fixtures";
import { run } from "./submitStockAdjustment";

describe("submitStockAdjustment", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["inventory:inventory:submitStockAdjustment"],
  };

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: "nonexistent" }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StockAdjustmentNotFoundError);
    }
  });

  it("returns error when stock adjustment is not in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSubmittedAdjustment]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-2" }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusError);
    }
  });

  it("transitions stock adjustment from DRAFT to SUBMITTED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const submitted = { ...baseDraftAdjustment, status: "SUBMITTED" };

    mock.enqueueResults(
      [baseDraftAdjustment],
      [correctionIncreaseLine],
      [{ id: "execution-1" }],
      [{ id: "execution-line-1" }],
      [submitted],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-1" }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustment.status).toBe("SUBMITTED");
    }
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ status: "SUBMITTED" }),
    );
  });

  it("does not create inventory execution when line item validation fails", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-1" }, ctx, mockItemManagementQueries(null)),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotFoundError);
    }
    expect(mock.inserts).toHaveLength(0);
    expect(mock.updates).toHaveLength(0);
  });
});
