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

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

  it("returns error when standard cost without rate", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, { name: "Std Policy", costingMethod: "STANDARD_COST" }, ctx),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StandardCostRateRequiredError);
    }
  });

  it("creates FIFO policy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseFifoPolicy]);

    const result = await mock.withTx((trx) =>
      run(trx, { name: "FIFO Policy", costingMethod: "FIFO" }, ctx),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.valuationPolicy.costingMethod).toBe("FIFO");
    }
    expect(mock.inserts).toHaveLength(1);
  });

  it("creates AVCO policy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseAvcoPolicy]);

    const result = await mock.withTx((trx) =>
      run(trx, { name: "AVCO Policy", costingMethod: "AVCO" }, ctx),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.valuationPolicy.costingMethod).toBe("AVCO");
    }
    expect(mock.inserts).toHaveLength(1);
  });

  it("creates standard cost policy with rate", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStandardCostPolicy]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { name: "Standard Cost Policy", costingMethod: "STANDARD_COST", standardCostRate: 10.5 },
        ctx,
      ),
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.valuationPolicy.costingMethod).toBe("STANDARD_COST");
      expect(result.value.valuationPolicy.standardCostRate).toBe("10.5");
    }
    expect(mock.inserts).toHaveLength(1);
  });
});
