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

const builtins = (params: { itemType?: TailorAnyDBType }) => {
  const itemId = db.uuid().description("Foreign key to generated Item in item-management");
  return {
    productId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: product },
        backward: "productVariants",
      })
      .description("Foreign key to Product"),
    axisValueKey: db
      .string()
      .description("Canonical key derived from sorted axis value IDs (e.g., value-1|value-3)"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "productVariants",
        })
      : itemId,
  };
};

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

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

export function createProductVariantType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProductVariantTypeParams<F>,
) {
  return db
    .type("ProductVariant", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["productId", "axisValueKey"],
      unique: true,
      name: "product_variant_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const productVariant = createProductVariantType({});
