import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CountLineNotFoundError, CountLineNotPendingError } from "../lib/errors.generated";
import { basePendingCountLine, baseApprovedCountLine } from "../testing/fixtures";
import { run } from "./rejectCountLine";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("returns error when not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { countLineId: "nonexistent" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CountLineNotFoundError);
    }
  });

  it("returns error when not pending", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseApprovedCountLine); // APPROVED

    const result = await run(db, { countLineId: "count-line-2" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CountLineNotPendingError);
    }
  });

  it("rejects line", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const rejectedLine = { ...basePendingCountLine, status: "REJECTED" };

    spies.select.mockReturnValueOnce(basePendingCountLine);
    spies.update.mockReturnValue(rejectedLine);

    const result = await run(db, { countLineId: "count-line-1" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.countLine.status).toBe("REJECTED");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("sets line to RECOUNT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const recountLine = { ...basePendingCountLine, status: "RECOUNT" };

    spies.select.mockReturnValueOnce(basePendingCountLine);
    spies.update.mockReturnValue(recountLine);

    const result = await run(db, { countLineId: "count-line-1", recount: true }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.countLine.status).toBe("RECOUNT");
    }
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ status: "RECOUNT" }));
  });
});
