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

const builtins = (params: { itemType?: TailorAnyDBType }) => {
  const itemId = db.uuid().description("Foreign key to Item");
  return {
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "itemValuations",
        })
      : itemId,
    valuationPolicyId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: valuationPolicy },
        backward: "itemValuations",
      })
      .description("Foreign key to ValuationPolicy"),
    totalQuantity: db.decimal().description("Total quantity in inventory"),
    totalValue: db.decimal().description("Total inventory value"),
    costPerUnit: db.decimal().description("Computed cost per unit (totalValue / totalQuantity)"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

export function createItemValuationType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateItemValuationTypeParams<F>,
) {
  return db
    .type("ItemValuation", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["itemId", "valuationPolicyId"],
      unique: true,
      name: "item_valuation_item_policy_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const itemValuation = createItemValuationType({});
