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

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

const builtins = (params: { itemType?: TailorAnyDBType }) => {
  const itemId = db.uuid().description("Foreign key to Item");
  return {
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "stockLevels",
        })
      : itemId,
    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"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

export function createStockLevelType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateStockLevelTypeParams<F>,
) {
  return db
    .type("StockLevel", {
      ...builtins(params),
      ...((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({});
