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

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

export function createProductionOrderMaterialRequirementType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProductionOrderMaterialRequirementTypeParams<F>) {
  return db
    .type("ProductionOrderMaterialRequirement", {
      productionOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.productionOrderType },
          backward: "materialRequirements",
        })
        .description("Foreign key to ProductionOrder"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "productionOrderMaterialRequirements",
        })
        .description("Foreign key to Item – the required material"),
      requiredQuantity: db.float().description("Required quantity of the material"),
      unitOfMeasure: db
        .string({ optional: true })
        .description("Unit of measure for the required quantity"),
      plannedUnitCost: db
        .float({ optional: true })
        .description("Planned cost per unit of the material"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const productionOrderMaterialRequirement = createProductionOrderMaterialRequirementType({
  productionOrderType: productionOrder,
  itemType: itemStub,
});
