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

const builtins = (params: { itemType?: TailorAnyDBType }) => {
  const itemId = db.uuid().description("Foreign key to Item");
  return {
    serialNumber: db.string().description("Serial number value, unique per item"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "serialNumbers",
        })
      : itemId,
    storageLocationId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: storageLocation },
        backward: "serialNumbers",
      })
      .description("Current storage location of the serial-tracked unit"),
    status: db
      .enum(serialNumberLifecycle.states)
      .description("Lifecycle status: AVAILABLE, ISSUED, RETURNED, SCRAPPED"),
  };
};

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

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

export function createSerialNumberType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSerialNumberTypeParams<F>,
) {
  return db
    .type("SerialNumber", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["serialNumber", "itemId"],
      unique: true,
      name: "serial_number_item_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const serialNumber = createSerialNumberType({});
