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 { productLifecycle } from "./product.lifecycle.generated";

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

export function createProductType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateProductTypeParams<F>,
) {
  return db
    .type("Product", {
      code: db.string().unique().description("Globally unique, immutable product code"),
      name: db.string().description("Product display name"),
      description: db.string({ optional: true }).description("Optional product description"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "products",
        })
        .description("Foreign key to Unit"),
      status: db.enum(productLifecycle.states).description("Lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const product = createProductType({ unitType: unitStub });
