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

export interface CreatePurchaseOrderRevisionTypeParams {
  userType?: TailorAnyDBType;
}

export function createPurchaseOrderRevisionType(params: CreatePurchaseOrderRevisionTypeParams) {
  const amendedByUserId = db
    .uuid({ optional: true })
    .description(
      "User who initiated this amendment. Set explicitly by amendOrderedPurchaseOrder from CommandContext. Optional for backward compatibility with rows written before this column existed.",
    );
  return db
    .type("PurchaseOrderRevision", {
      purchaseOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseOrder },
          backward: "revisions",
        })
        .description("Foreign key to PurchaseOrder"),
      revisionNumber: db
        .int()
        .description(
          "Sequential revision number per purchase order, starting at 1 on the first amendment",
        ),
      reason: db.string({ optional: true }).description("Free-text amendment reason"),
      amendedByUserId: params.userType
        ? amendedByUserId.relation({
            type: "n-1",
            toward: { type: params.userType },
            backward: "amendedPurchaseOrderRevisions",
          })
        : amendedByUserId,
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["purchaseOrderId", "revisionNumber"],
      unique: true,
      name: "purchase_order_revision_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseOrderRevision = createPurchaseOrderRevisionType({});
