import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { lot } from "./lot";
import { storageLocation } from "./storageLocation";

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

export function createLotStockLevelType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateLotStockLevelTypeParams<F>,
) {
  return db
    .type("LotStockLevel", {
      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 (under inspection/quarantine); available = onHand - blocked",
        ),
      ...((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({});
