import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { item as itemStub } from "../lib/_db_deps";
import { storageLocation } from "./storageLocation";

export const STOCK_TYPES = ["AVAILABLE", "BLOCKED", "IN_TRANSIT"] as const;

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"),
      stockType: db
        .enum([...STOCK_TYPES] as [string, ...string[]])
        .description("Current stock type: AVAILABLE, BLOCKED, or IN_TRANSIT"),
      quantity: db.decimal().description("Current quantity in this stock type and dimension set"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["itemId", "storageLocationId", "stockType"],
      unique: true,
      name: "stock_level_item_location_type_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const stockLevel = createStockLevelType({});
