import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { ValuationPolicyCostingMethod } from "../generated/enums";
import type { Transaction } from "../generated/kysely-tailordb";
import { StandardCostRateRequiredError } from "../lib/errors.generated";

export interface CreateValuationPolicyInput {
  name: string;
  costingMethod: ValuationPolicyCostingMethod;
  standardCostRate?: number | null;
}

/**
 * Function: createValuationPolicy
 *
 * Creates a new valuation policy that defines the costing method used to
 * calculate inventory value. Supported costing methods are FIFO, AVCO,
 * and STANDARD_COST.
 */
export async function run(
  db: Transaction,
  input: CreateValuationPolicyInput,
  _ctx: CommandContext,
) {
  const { name, costingMethod, standardCostRate } = input;

  // 1. Require standardCostRate for STANDARD_COST
  if (costingMethod === "STANDARD_COST" && standardCostRate == null) {
    return err(new StandardCostRateRequiredError(costingMethod));
  }

  // 2. Create valuation policy
  const policy = await db
    .insertInto("ValuationPolicy")
    .values({
      name,
      costingMethod,
      standardCostRate: standardCostRate != null ? String(standardCostRate) : null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ valuationPolicy: policy });
}
