import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import {
  businessPartner as businessPartnerStub,
  company as companyStub,
  site as siteStub,
} from "../lib/_db_deps";
import { salesOrder } from "./salesOrder";

export const SHIPMENT_STATUSES: [string, string] = ["DRAFT", "POSTED"];

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

export function createShipmentType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateShipmentTypeParams<F>,
) {
  return db
    .type("Shipment", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "shipments",
        })
        .description("Foreign key to Company"),
      salesOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.salesOrderType ?? salesOrder },
          backward: "shipments",
        })
        .description("Foreign key to SalesOrder"),
      customerId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.customerType ?? businessPartnerStub },
          backward: "shipments",
        })
        .description("Optional customer"),
      shipFromSiteId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.siteType ?? siteStub },
          backward: "shipments",
        })
        .description("Optional ship-from site"),
      shipmentDate: db.date().description("Shipment date"),
      status: db.enum(SHIPMENT_STATUSES).description("Shipment lifecycle status"),
      trackingNumber: db.string({ optional: true }).description("Tracking number"),
      shippingAddressSnapshot: db
        .string({ optional: true })
        .description("Serialized shipping address snapshot"),
      inventoryHandoff: db
        .string({ optional: true })
        .description("Serialized outbound inventory handoff"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const shipment = createShipmentType({});
