import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseSubmittedAdjustment);

    const result = await run(
      db,
      { 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 { db, spies } = createMockDb<Transaction>();
    const submitted = { ...baseDraftAdjustment, status: "SUBMITTED" };

    spies.select
      .mockReturnValueOnce(baseDraftAdjustment)
      .mockReturnValueOnce([correctionIncreaseLine]);
    spies.insert
      .mockReturnValueOnce({ id: "execution-1" })
      .mockReturnValueOnce([{ id: "execution-line-1" }]);
    spies.update.mockReturnValue(submitted);

    const result = await run(
      db,
      { id: "adjustment-1" },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustment.status).toBe("SUBMITTED");
    }
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ status: "SUBMITTED" }));
  });

  it("does not create inventory execution when line item validation fails", async () => {
    const { db, spies } = createMockDb<Transaction>();

    spies.select
      .mockReturnValueOnce(baseDraftAdjustment)
      .mockReturnValueOnce([correctionIncreaseLine]);

    const result = await run(db, { id: "adjustment-1" }, ctx, mockItemManagementQueries(null));

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotFoundError);
    }
    expect(spies.insert).not.toHaveBeenCalled();
    expect(spies.update).not.toHaveBeenCalled();
  });
});
