import { db } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { purchaseOrder } from "./purchaseOrder";

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

export function createPurchaseOrderLineRevisionType() {
  return db
    .type("PurchaseOrderLineRevision", {
      purchaseOrderLineId: db
        .uuid()
        .description("ID of the PurchaseOrderLine at the time of the revision (no FK constraint)"),
      purchaseOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseOrder },
          backward: "lineRevisions",
        })
        .description("Foreign key to PurchaseOrder — allows lookup even after line deletion"),
      action: db.enum(REVISION_ACTIONS).description("What happened to the line in this revision"),
      revisionNumber: db.int().description("PO revision number at the time of this change"),
      quantity: db.decimal().description("Ordered quantity at the time of the snapshot"),
      unitPrice: db.decimal().description("Unit price at the time of the snapshot"),
      itemId: db.uuid().description("Item ID at the time of the snapshot"),
      unitId: db.uuid({ optional: true }).description("Unit ID at the time of the snapshot"),
      receivingSiteId: db
        .uuid({ optional: true })
        .description("Receiving site ID at the time of the snapshot"),

      reason: db.string({ optional: true }).description("Amendment reason"),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseOrderLineRevision = createPurchaseOrderLineRevisionType();
