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

const builtins = {
  lotId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: lot },
      backward: "lotStockLevels",
    })
    .description("Foreign key to Lot"),
  storageLocationId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: storageLocation },
      backward: "lotStockLevels",
    })
    .description("Foreign key to StorageLocation"),
  onHand: db.decimal().description("Quantity of this lot on hand at this location"),
  blocked: db
    .decimal()
    .description("Portion of onHand that is blocked or quarantined; available = onHand - blocked"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

export function createLotStockLevelType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateLotStockLevelTypeParams<F>,
) {
  return db
    .type("LotStockLevel", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["lotId", "storageLocationId"],
      unique: true,
      name: "lot_stock_level_lot_location_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const lotStockLevel = createLotStockLevelType({});
