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

const builtins = (params: {
  companyType?: TailorAnyDBType;
  customerType?: TailorAnyDBType;
  siteType?: TailorAnyDBType;
}) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const customerId = db.uuid({ optional: true }).description("Optional customer");
  const shipFromSiteId = db.uuid({ optional: true }).description("Optional ship-from site");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "shipments",
        })
      : companyId,
    salesOrderId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: salesOrder },
        backward: "shipments",
      })
      .description("Foreign key to SalesOrder"),
    customerId: params.customerType
      ? customerId.relation({
          type: "n-1",
          toward: { type: params.customerType },
          backward: "shipments",
        })
      : customerId,
    shipFromSiteId: params.siteType
      ? shipFromSiteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "shipments",
        })
      : shipFromSiteId,
    shipmentDate: db.date().description("Shipment date"),
    status: db.enum(shipmentLifecycle.states).description("Shipment lifecycle status"),
    trackingNumber: db.string({ optional: true }).description("Tracking number"),
    shippingAddressSnapshot: db
      .string({ optional: true })
      .description("Serialized shipping address snapshot"),
  };
};

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

export interface CreateShipmentTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: NoReservedFields<F, ReservedFields>;
  companyType?: TailorAnyDBType;
  customerType?: TailorAnyDBType;
  siteType?: TailorAnyDBType;
}

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

export const shipment = createShipmentType({});
