import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { lot } from "./lot";
import { serialNumber } from "./serialNumber";
import { transferOrder } from "./transferOrder";

const builtins = (params: { itemType?: TailorAnyDBType; unitType?: TailorAnyDBType }) => {
  const itemId = db.uuid().description("Item being transferred");
  const unitId = db
    .uuid()
    .description("Business unit for ordered, shipped, and received quantities");
  return {
    transferOrderId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: transferOrder },
        backward: "lines",
      })
      .description("Foreign key to TransferOrder header"),
    itemId: params.itemType
      ? itemId.relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "transferOrderLines",
        })
      : itemId,
    unitId: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "transferOrderLines",
        })
      : unitId,
    orderedQuantity: db.decimal().description("Quantity requested for transfer"),
    shippedQuantity: db.decimal().description("Cumulative quantity shipped"),
    receivedQuantity: db.decimal().description("Cumulative quantity received"),
    lotId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: lot },
        backward: "transferOrderLines",
      })
      .description("Optional Lot constraint for this transfer line"),
    serialNumberId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: serialNumber },
        backward: "transferOrderLines",
      })
      .description("Optional SerialNumber constraint for this transfer line"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

export interface CreateTransferOrderLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
  itemType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
}

export function createTransferOrderLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateTransferOrderLineTypeParams<F>,
) {
  return db
    .type("TransferOrderLine", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const transferOrderLine = createTransferOrderLineType({});
