import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { item as itemStub } from "../lib/_db_deps";
import { inventoryLedger } from "./inventoryLedger";
import { valuationPolicy } from "./valuationPolicy";

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

export function createCostLayerType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateCostLayerTypeParams<F>,
) {
  return db
    .type("CostLayer", {
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: itemStub },
          backward: "costLayers",
        })
        .description("Foreign key to Item"),
      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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const costLayer = createCostLayerType({});
