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

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

export function createProductVariantType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProductVariantTypeParams<F>,
) {
  return db
    .type("ProductVariant", {
      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: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "productVariants",
        })
        .description("Foreign key to generated Item in item-management"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["productId", "axisValueKey"],
      unique: true,
      name: "product_variant_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const productVariant = createProductVariantType({ itemType: itemStub });
