import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseItemValuation, baseFifoPolicy } from "../testing/fixtures";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { ItemValuationNotFoundError } from "../lib/errors.generated";
import { run } from "./getItemValuation";

describe("getItemValuation", () => {
  it("returns valuation when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseItemValuation);
    spies.select.mockReturnValueOnce(baseFifoPolicy);

    const result = await run(db, {
      itemId: baseItemValuation.itemId,
      valuationPolicyId: baseItemValuation.valuationPolicyId,
    });
    const { itemValuation } = expectOk<{
      itemValuation: { id: string };
      valuationPolicy: unknown;
    }>(result as never);

    expect(itemValuation).toMatchObject({ id: baseItemValuation.id });
  });

  it("includes costing method from policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseItemValuation);
    spies.select.mockReturnValueOnce(baseFifoPolicy);

    const result = await run(db, {
      itemId: baseItemValuation.itemId,
      valuationPolicyId: baseItemValuation.valuationPolicyId,
    });
    const { valuationPolicy } = expectOk<{
      itemValuation: unknown;
      valuationPolicy: { costingMethod: string };
    }>(result as never);

    expect(valuationPolicy.costingMethod).toBe("FIFO");
  });

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

    const result = await run(db, {
      itemId: "nonexistent-item",
      valuationPolicyId: "policy-1",
    });
    expectErr(result as never, ItemValuationNotFoundError);
  });

  it("costPerUnit equals totalValue divided by totalQuantity", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseItemValuation);
    spies.select.mockReturnValueOnce(baseFifoPolicy);

    const result = await run(db, {
      itemId: baseItemValuation.itemId,
      valuationPolicyId: baseItemValuation.valuationPolicyId,
    });
    const { itemValuation } = expectOk<{
      itemValuation: { costPerUnit: number; totalValue: number; totalQuantity: number };
      valuationPolicy: unknown;
    }>(result as never);

    expect(itemValuation.costPerUnit).toBe(10);
    expect(itemValuation.costPerUnit).toBe(itemValuation.totalValue / itemValuation.totalQuantity);
  });
});
