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: "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"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const productionOrderRoutingSnapshot = createProductionOrderRoutingSnapshotType({});
