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

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

  it("returns error when invalid costing method", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(db, { name: "Bad Policy", costingMethod: "LIFO" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidCostingMethodError);
    }
  });

  it("returns error when standard cost without rate", async () => {
    const { db } = createMockDb<Transaction>();

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.insert.mockReturnValue(baseFifoPolicy);

    const result = await run(db, { name: "FIFO Policy", costingMethod: "FIFO" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.valuationPolicy.costingMethod).toBe("FIFO");
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("creates AVCO policy", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.insert.mockReturnValue(baseAvcoPolicy);

    const result = await run(db, { name: "AVCO Policy", costingMethod: "AVCO" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.valuationPolicy.costingMethod).toBe("AVCO");
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("creates standard cost policy with rate", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.insert.mockReturnValue(baseStandardCostPolicy);

    const result = await run(
      db,
      { 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(spies.insert).toHaveBeenCalled();
  });
});
