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

export const FIELD_CHANGE_RECORD_TYPES = ["HEADER", "LINE"] as const;

export const FIELD_CHANGE_KINDS = ["ADDED", "MODIFIED", "REMOVED"] as const;

export function createPurchaseOrderFieldChangeType() {
  return db
    .type("PurchaseOrderFieldChange", {
      revisionId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseOrderRevision },
          backward: "fieldChanges",
        })
        .description("Foreign key to PurchaseOrderRevision (envelope)"),
      recordType: db
        .enum(FIELD_CHANGE_RECORD_TYPES)
        .description("Whether the changed field belongs to the PO header or one of its lines"),
      recordId: db
        .uuid()
        .description("ID of the affected PurchaseOrder or PurchaseOrderLine (no FK constraint)"),
      fieldName: db
        .string()
        .description("Name of the changed field, including app-extension fields"),
      changeKind: db
        .enum(FIELD_CHANGE_KINDS)
        .description("ADDED, MODIFIED, or REMOVED — describes the nature of the change"),
      oldValue: db
        .string({ optional: true })
        .description("Pre-change value as a string; null for ADDED entries"),
      newValue: db
        .string({ optional: true })
        .description("Post-change value as a string; null for REMOVED entries"),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseOrderFieldChange = createPurchaseOrderFieldChangeType();
