import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";

export const COSTING_METHODS = ["FIFO", "AVCO", "STANDARD_COST"] as const;

const builtins = {
  name: db.string().description("Policy display name"),
  costingMethod: db
    .enum(COSTING_METHODS)
    .description("Costing method: FIFO, AVCO, or STANDARD_COST"),
  standardCostRate: db
    .decimal({ optional: true })
    .description("Fixed cost rate, required when costingMethod is STANDARD_COST"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

export interface CreateValuationPolicyTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
}

export function createValuationPolicyType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateValuationPolicyTypeParams<F>,
) {
  return db
    .type("ValuationPolicy", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const valuationPolicy = createValuationPolicyType({});
