import { defaultGqlPermission, defaultPermission } from "@tailor-platform/erp-kit/core";
import { db } from "@tailor-platform/sdk";
import { manufacturingCostSummary } from "./manufacturingCostSummary";

export const VARIANCE_TYPES = [
  "MATERIAL_PRICE",
  "MATERIAL_USAGE",
  "LABOR_RATE",
  "LABOR_EFFICIENCY",
  "MACHINE_RATE",
  "MACHINE_EFFICIENCY",
  "SCRAP",
  "YIELD",
] as const;

export function createCostVarianceLineType() {
  return db
    .type("CostVarianceLine", {
      costSummaryId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: manufacturingCostSummary },
          backward: "varianceLines",
        })
        .description("Foreign key to ManufacturingCostSummary"),
      varianceType: db
        .enum(VARIANCE_TYPES)
        .description(
          "Variance type: MATERIAL_PRICE, MATERIAL_USAGE, LABOR_RATE, LABOR_EFFICIENCY, MACHINE_RATE, MACHINE_EFFICIENCY, SCRAP, YIELD",
        ),
      amount: db.float().description("Variance amount"),
      accountReference: db
        .string({ optional: true })
        .description("Optional account reference for settlement"),
      variancePercentage: db.float({ optional: true }).description("Variance as a percentage"),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const costVarianceLine = createCostVarianceLineType();
