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

const builtins = (params: { unitType?: TailorAnyDBType }) => {
  const unitId = db.uuid().description("Foreign key to Unit");
  return {
    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: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "items",
        })
      : unitId,
    status: db.enum(itemLifecycle.states).description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
  };
};

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

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

export function createItemType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateItemTypeParams<F>,
) {
  return db
    .type("Item", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const item = createItemType({});
