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

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

export function createProductionOrderRoutingSnapshotType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProductionOrderRoutingSnapshotTypeParams<F>) {
  return db
    .type("ProductionOrderRoutingSnapshot", {
      productionOrderId: db
        .uuid()
        .relation({
          type: "1-1",
          toward: { type: params.productionOrderType },
          backward: "routingSnapshot",
        })
        .description("Foreign key to ProductionOrder (one snapshot per order)"),
      routingId: db.uuid().description("Routing ID reference for the snapshot"),
      snapshotData: db
        .string({ optional: true })
        .description("JSON blob containing the full routing snapshot"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const productionOrderRoutingSnapshot = createProductionOrderRoutingSnapshotType({
  productionOrderType: productionOrder,
});
