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

const builtins = (params: { itemType?: TailorAnyDBType }) => {
  const itemId = db.uuid().description("Foreign key to Item – the required material");
  return {
    productionOrderId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: productionOrder },
        backward: "materialRequirements",
      })
      .description("Foreign key to ProductionOrder"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "productionOrderMaterialRequirements",
        })
      : itemId,
    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"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

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

export const productionOrderMaterialRequirement = createProductionOrderMaterialRequirementType({});
