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

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

export function createStockLevelType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateStockLevelTypeParams<F>,
) {
  return db
    .type("StockLevel", {
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: itemStub },
          backward: "stockLevels",
        })
        .description("Foreign key to Item"),
      storageLocationId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: storageLocation },
          backward: "stockLevels",
        })
        .description("Foreign key to StorageLocation"),
      onHand: db.float().description("Quantity physically present"),
      reserved: db.float().description("Quantity reserved for outbound orders"),
      incoming: db.float().description("Quantity expected from inbound orders"),
      blocked: db.float().description("Quantity blocked from use"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["itemId", "storageLocationId"],
      unique: true,
      name: "stock_level_item_location_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const stockLevel = createStockLevelType({});
