import type { DB } from "../generated/kysely-tailordb";
import { ItemValuationNotFoundError } from "../lib/errors.generated";
import { ok, err, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export interface GetItemValuationInput {
  itemId: string;
  valuationPolicyId: string;
}

export async function run(db: ReadonlyDB<DB>, input: GetItemValuationInput) {
  const itemValuation = await db
    .selectFrom("ItemValuation")
    .selectAll()
    .where("itemId", "=", input.itemId)
    .where("valuationPolicyId", "=", input.valuationPolicyId)
    .executeTakeFirst();

  if (!itemValuation) {
    return err(new ItemValuationNotFoundError(input.itemId));
  }

  const valuationPolicy = await db
    .selectFrom("ValuationPolicy")
    .selectAll()
    .where("id", "=", itemValuation.valuationPolicyId)
    .executeTakeFirst();

  return ok({ itemValuation, valuationPolicy: valuationPolicy ?? null });
}
