import {
  db,
  type TailorAnyDBField,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { item as itemStub } from "../lib/_db_deps";
import { stockMovement } from "./stockMovement";
import { storageLocation } from "./storageLocation";
import { lot } from "./lot";
import { serialNumber } from "./serialNumber";

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

export function createStockMoveLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateStockMoveLineTypeParams<F>,
) {
  return db
    .type("StockMoveLine", {
      stockMovementId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: stockMovement },
          backward: "stockMoveLines",
        })
        .description("Foreign key to StockMovement"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: itemStub },
          backward: "stockMoveLines",
        })
        .description("Foreign key to Item"),
      quantity: db.float().description("Quantity to move, must be greater than 0"),
      sourceLocationId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: storageLocation },
          backward: "outboundMoveLines",
        })
        .description("Source storage location"),
      destinationLocationId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: storageLocation },
          backward: "inboundMoveLines",
        })
        .description("Destination storage location"),
      lotId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: lot },
          backward: "stockMoveLines",
        })
        .description("Optional foreign key to Lot for lot-tracked items"),
      serialNumberId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: serialNumber },
          backward: "stockMoveLines",
        })
        .description("Optional foreign key to SerialNumber for serial-tracked items"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const stockMoveLine = createStockMoveLineType({});
