import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { unit as unitStub } from "../lib/_db_deps";
import { salesOrderLine } from "./salesOrderLine";
import { shipment } from "./shipment";

export interface CreateShipmentLineTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  shipmentType?: TailorAnyDBType;
  salesOrderLineType?: TailorAnyDBType;
  unitType?: TailorAnyDBType;
}

export function createShipmentLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateShipmentLineTypeParams<F>,
) {
  return db
    .type("ShipmentLine", {
      shipmentId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.shipmentType ?? shipment },
          backward: "lines",
        })
        .description("Foreign key to Shipment"),
      salesOrderLineId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.salesOrderLineType ?? salesOrderLine },
          backward: "shipmentLines",
        })
        .description("Foreign key to SalesOrderLine"),
      quantity: db.float().description("Shipped quantity"),
      unitId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.unitType ?? unitStub },
          backward: "shipmentLines",
        })
        .description("Optional unit"),
      trackingReference: db.string({ optional: true }).description("Tracking reference"),
      requiresInventoryHandoff: db.bool().description("Whether inventory handoff is required"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const shipmentLine = createShipmentLineType({});
