import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { productionOrder } from "./productionOrder";

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

export function createProductionOrderBomSnapshotType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProductionOrderBomSnapshotTypeParams<F>) {
  return db
    .type("ProductionOrderBomSnapshot", {
      productionOrderId: db
        .uuid()
        .relation({
          type: "1-1",
          toward: { type: params.productionOrderType },
          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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const productionOrderBomSnapshot = createProductionOrderBomSnapshotType({
  productionOrderType: productionOrder,
});
