import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { inventoryLedger } from "./inventoryLedger";
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: "costLayers",
        })
      : itemId,
    valuationPolicyId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: valuationPolicy },
        backward: "costLayers",
      })
      .description("Foreign key to ValuationPolicy (FIFO)"),
    inventoryLedgerId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: inventoryLedger },
        backward: "costLayers",
      })
      .description("Foreign key to the InventoryLedger entry that created this cost layer"),
    quantity: db.decimal().description("Original quantity received in this layer"),
    unitCost: db.decimal().description("Cost per unit for this layer"),
    remainingQuantity: db.decimal().description("Unconsumed quantity remaining in this layer"),
  };
};

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

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

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

export const costLayer = createCostLayerType({});
