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

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

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

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

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

export const product = createProductType({});
