import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { ItemValuationNotFoundError } from "../lib/errors.generated";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { baseItemValuation, baseFifoPolicy } from "../testing/fixtures";
import { run } from "./getItemValuation";

describe("getItemValuation", () => {
  it("returns valuation when found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItemValuation], [baseFifoPolicy]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItemValuation], [baseFifoPolicy]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

  it("costPerUnit equals totalValue divided by totalQuantity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItemValuation], [baseFifoPolicy]);

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

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