import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
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.float().description("Quantity of this lot on hand at this location"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["lotId", "storageLocationId"],
      unique: true,
      name: "lot_stock_level_lot_location_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const lotStockLevel = createLotStockLevelType({});
