import {
  db,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} 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 interface CreateCostVarianceLineTypeParams {
  costSummaryType: TailorAnyDBType;
}

export function createCostVarianceLineType(params: CreateCostVarianceLineTypeParams) {
  return db
    .type("CostVarianceLine", {
      costSummaryId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.costSummaryType },
          backward: "varianceLines",
        })
        .description("Foreign key to ManufacturingCostSummary"),
      varianceType: db
        .enum([...VARIANCE_TYPES] as [string, ...string[]])
        .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(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const costVarianceLine = createCostVarianceLineType({
  costSummaryType: manufacturingCostSummary,
});
