import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { unit as unitStub } from "../lib/_db_deps";
import { itemLifecycle } from "./item.lifecycle.generated";

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

export function createItemType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateItemTypeParams<F>,
) {
  return db
    .type("Item", {
      sku: db.string().unique().description("Globally unique, immutable SKU identifier"),
      name: db.string().description("Item display name"),
      barcode: db.string({ optional: true }).unique().description("Optional unique barcode"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "items",
        })
        .description("Foreign key to Unit"),
      status: db
        .enum(itemLifecycle.states)
        .description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const item = createItemType({ unitType: unitStub });
