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

const builtins = (params: { unitType?: TailorAnyDBType }) => {
  const unitId = db.uuid({ optional: true }).description("Optional unit");
  return {
    shipmentId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: shipment },
        backward: "lines",
      })
      .description("Foreign key to Shipment"),
    salesOrderLineId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: salesOrderLine },
        backward: "shipmentLines",
      })
      .description("Foreign key to SalesOrderLine"),
    quantity: db.float().description("Shipped quantity"),
    unitId: params.unitType
      ? unitId.relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "shipmentLines",
        })
      : unitId,
    trackingReference: db.string({ optional: true }).description("Tracking reference"),
  };
};

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

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

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

export const shipmentLine = createShipmentLineType({});
