import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ValuationPolicyNotFoundError,
  StandardCostRateRequiredError,
} from "../lib/errors.generated";
import { baseFifoPolicy, baseAvcoPolicy, baseStandardCostPolicy } from "../testing/fixtures";
import { run } from "./updateValuationPolicy";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

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

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

  it("updates policy name", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedPolicy = { ...baseFifoPolicy, name: "Renamed FIFO" };
    spies.select.mockReturnValueOnce(baseFifoPolicy); // existing policy
    spies.update.mockReturnValue(updatedPolicy);

    const result = await run(db, { id: "policy-1", name: "Renamed FIFO" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.valuationPolicy.name).toBe("Renamed FIFO");
      expect(result.value.revaluationEvent).toBe(false);
    }
  });

  it("returns error when standard cost rate required", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // Changing from AVCO to STANDARD_COST without providing standardCostRate
    spies.select.mockReturnValueOnce(baseAvcoPolicy); // existing policy (no standardCostRate)

    const result = await run(db, { id: "policy-2", costingMethod: "STANDARD_COST" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StandardCostRateRequiredError);
    }
  });

  it("updates standard cost rate and emits revaluation event", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedPolicy = { ...baseStandardCostPolicy, standardCostRate: 15.0 };
    spies.select.mockReturnValueOnce(baseStandardCostPolicy); // existing policy
    spies.update.mockReturnValue(updatedPolicy);

    const result = await run(db, { id: "policy-3", standardCostRate: 15.0 }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.valuationPolicy.standardCostRate).toBe(15.0);
      expect(result.value.revaluationEvent).toBe(true);
    }
  });
});
