import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { item as itemStub } from "../lib/_db_deps";
import { valuationPolicy } from "./valuationPolicy";
import { stockMovement } from "./stockMovement";

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)"),
      stockMovementId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: stockMovement },
          backward: "costLayers",
        })
        .description("Foreign key to the goods receipt StockMovement"),
      quantity: db.float().description("Original quantity received in this layer"),
      unitCost: db.float().description("Cost per unit for this layer"),
      remainingQuantity: db.float().description("Unconsumed quantity remaining in this layer"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const costLayer = createCostLayerType({});
