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

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

export function createProductionOrderCostBaselineType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateProductionOrderCostBaselineTypeParams<F>) {
  return db
    .type("ProductionOrderCostBaseline", {
      productionOrderId: db
        .uuid()
        .relation({
          type: "1-1",
          toward: { type: params.productionOrderType },
          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)"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const productionOrderCostBaseline = createProductionOrderCostBaselineType({
  productionOrderType: productionOrder,
});
