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: "costBaseline",
    })
    .description("Foreign key to ProductionOrder (one baseline per order)"),
  plannedMaterialCost: db.float().description("Planned total material cost"),
  plannedLaborCost: db.float().description("Planned total labor cost"),
  plannedMachineCost: db.float().description("Planned total machine cost"),
  plannedOverheadCost: db.float().description("Planned total overhead cost"),
  currencyCode: db.string().description("ISO 4217 currency code (e.g., USD)"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

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

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

export const productionOrderCostBaseline = createProductionOrderCostBaselineType({});
