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

export const CHANGE_ORDER_STATUSES: [string, string, string, string, string, string] = [
  "DRAFT",
  "SUBMITTED",
  "APPROVED",
  "APPLIED",
  "REJECTED",
  "CANCELLED",
];

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

export function createPurchaseChangeOrderType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseChangeOrderTypeParams<F>,
) {
  return db
    .type("PurchaseChangeOrder", {
      purchaseOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseOrder },
          backward: "purchaseChangeOrders",
        })
        .description("Foreign key to PurchaseOrder"),
      fromRevisionNumber: db.int().description("PO revision number at change order creation"),
      reason: db.string({ optional: true }).description("Business justification for the change"),
      changeOrderStatus: db
        .enum(CHANGE_ORDER_STATUSES)
        .description("Change order lifecycle status"),
      rejectionReason: db
        .string({ optional: true })
        .description("Reason provided when the change order is rejected"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const purchaseChangeOrder = createPurchaseChangeOrderType({});
