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 "./approveCountLine";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

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

    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); // already 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("approves line", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const approvedLine = { ...basePendingCountLine, status: "APPROVED" };

    spies.select.mockReturnValueOnce(basePendingCountLine); // line lookup
    spies.update.mockReturnValue(approvedLine);
    spies.insert.mockReturnValue({ id: "adjustment-new" }); // adjustment created

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

  it("generates adjustment for non-zero variance", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // basePendingCountLine has variance: -2
    const approvedLine = { ...basePendingCountLine, status: "APPROVED" };

    spies.select.mockReturnValueOnce(basePendingCountLine);
    spies.update.mockReturnValue(approvedLine);
    spies.insert.mockReturnValue({ id: "adjustment-new" });

    const result = await run(db, { countLineId: "count-line-1" }, ctx);
    expect(result.ok).toBe(true);
    expect(spies.insert).toHaveBeenCalled();
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({
        reasonCode: "inventory-count",
        quantityDelta: -2,
      }),
    );
  });

  it("zero variance approved without adjustment", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const zeroVarianceLine = { ...basePendingCountLine, variance: 0 };
    const approvedLine = { ...zeroVarianceLine, status: "APPROVED" };

    spies.select.mockReturnValueOnce(zeroVarianceLine);
    spies.update.mockReturnValue(approvedLine);

    const result = await run(db, { countLineId: "count-line-1" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.countLine.status).toBe("APPROVED");
    }
    // No insert should have been called for adjustment
    expect(spies.insert).not.toHaveBeenCalled();
  });
});
