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

export const SERIAL_NUMBER_STATUSES = ["AVAILABLE", "ISSUED", "RETURNED", "SCRAPPED"] as const;

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

export function createSerialNumberType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateSerialNumberTypeParams<F>,
) {
  return db
    .type("SerialNumber", {
      serialNumber: db.string().description("Serial number value, unique per item"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: itemStub },
          backward: "serialNumbers",
        })
        .description("Foreign key to Item"),
      storageLocationId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: storageLocation },
          backward: "serialNumbers",
        })
        .description("Current storage location of the serial-tracked unit"),
      status: db
        .enum([...SERIAL_NUMBER_STATUSES] as [string, ...string[]])
        .description("Lifecycle status: AVAILABLE, ISSUED, RETURNED, SCRAPPED"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["serialNumber", "itemId"],
      unique: true,
      name: "serial_number_item_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const serialNumber = createSerialNumberType({});
