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 {
  ValuationPolicyNotFoundError,
  StandardCostRateRequiredError,
} from "../lib/errors.generated";
import { baseFifoPolicy, baseAvcoPolicy, baseStandardCostPolicy } from "../testing/fixtures";
import { run } from "./updateValuationPolicy";

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

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

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

  it("updates policy name", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedPolicy = { ...baseFifoPolicy, name: "Renamed FIFO" };
    mock.enqueueResults([baseFifoPolicy], [updatedPolicy]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    // Changing from AVCO to STANDARD_COST without providing standardCostRate
    mock.enqueueResults([baseAvcoPolicy]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const updatedPolicy = { ...baseStandardCostPolicy, standardCostRate: 15.0 };
    mock.enqueueResults([baseStandardCostPolicy], [updatedPolicy]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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);
    }
  });
});
