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

const builtins = {
  productionOrderId: db
    .uuid()
    .relation({
      type: "1-1",
      toward: { type: productionOrder },
      backward: "bomSnapshot",
    })
    .description("Foreign key to ProductionOrder (one snapshot per order)"),
  parentItemId: db.uuid().description("Item ID of the parent item in the BOM snapshot"),
  bomType: db.string().description("BOM type (e.g., STANDARD, PHANTOM)"),
  snapshotData: db
    .string({ optional: true })
    .description("JSON blob containing the full BOM snapshot"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const productionOrderBomSnapshot = createProductionOrderBomSnapshotType({});
