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

export const BASE_COST_SUMMARY_STATUSES = [
  "COLLECTING",
  "PENDING_VARIANCE_REVIEW",
  "VARIANCE_REVIEWED",
  "SETTLED",
] as const;

export interface CreateManufacturingCostSummaryTypeParams {
  productionOrderType: TailorAnyDBType;
}

export function createManufacturingCostSummaryType(
  params: CreateManufacturingCostSummaryTypeParams,
) {
  return db
    .type("ManufacturingCostSummary", {
      productionOrderId: db
        .uuid()
        .relation({
          type: "1-1",
          toward: { type: params.productionOrderType },
          backward: "manufacturingCostSummary",
        })
        .description("Foreign key to ProductionOrder"),
      plannedMaterialCost: db.float().description("Planned material cost"),
      plannedLaborCost: db.float().description("Planned labor cost"),
      plannedMachineCost: db.float().description("Planned machine cost"),
      plannedOverheadCost: db.float().description("Planned overhead cost"),
      actualMaterialCost: db.float().description("Actual material cost"),
      actualLaborCost: db.float().description("Actual labor cost"),
      actualMachineCost: db.float().description("Actual machine cost"),
      actualOverheadCost: db.float().description("Actual overhead cost"),
      currencyCode: db.string().description("Currency code (e.g. USD, EUR)"),
      reviewedDate: db
        .datetime({ optional: true })
        .description("Date when cost summary was reviewed"),
      reviewerNotes: db.string({ optional: true }).description("Notes from the reviewer"),
      status: db
        .enum([...BASE_COST_SUMMARY_STATUSES] as [string, ...string[]])
        .description(
          "Lifecycle status: COLLECTING, PENDING_VARIANCE_REVIEW, VARIANCE_REVIEWED, SETTLED",
        ),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const manufacturingCostSummary = createManufacturingCostSummaryType({
  productionOrderType: productionOrder,
});
