import { db } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { inventoryExecutionLine } from "../lib/_db_deps";
import { purchaseBillLine } from "./purchaseBillLine";

export function createThreeWayMatchEventType() {
  return db
    .type("ThreeWayMatchEvent", {
      purchaseBillLineId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseBillLine },
          backward: "threeWayMatchEvents",
        })
        .description("Foreign key to PurchaseBillLine"),
      inventoryExecutionLineId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: inventoryExecutionLine },
          backward: "threeWayMatchEvents",
        })
        .description("Foreign key to the InventoryExecutionLine used as goods-receipt evidence"),
      matchedQuantity: db.decimal().description("Matched quantity for this event"),
      matchedAt: db.date().description("Timestamp when this match event occurred"),
      matchedBy: db
        .string({ optional: true })
        .description("User or system that performed the match"),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const threeWayMatchEvent = createThreeWayMatchEventType();
