import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { unit as unitStub } from "../lib/_db_deps";

export const BASE_ITEM_STATUSES = ["DRAFT", "ACTIVE", "INACTIVE"] as const;

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

export function createItemType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateItemTypeParams<F>,
) {
  const statuses = [...BASE_ITEM_STATUSES, ...(params.additionalStatuses ?? [])] as [
    string,
    ...string[],
  ];

  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(statuses).description("Lifecycle status: DRAFT, ACTIVE, INACTIVE"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

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