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

const builtins = (params: { siteType?: TailorAnyDBType }) => {
  const sourceSiteId = db.uuid().description("Site where the transfer order originates");
  const destinationSiteId = db.uuid().description("Site where the transfer order is received");
  return {
    sourceSiteId: params.siteType
      ? sourceSiteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "sourceTransferOrders",
        })
      : sourceSiteId,
    destinationSiteId: params.siteType
      ? destinationSiteId.relation({
          type: "n-1",
          toward: { type: params.siteType, as: "destinationSite" },
          backward: "destinationTransferOrders",
        })
      : destinationSiteId,
    plannedShipmentDate: db
      .date()
      .description("Planned source-site shipping date used for stock reservation demand"),
    expectedReceiptDate: db
      .date()
      .description("Planned destination-site receiving date used for inbound supply planning"),
    status: db
      .enum(transferOrderLifecycle.states)
      .description("Document-control status: DRAFT, OPEN, or CLOSED"),
    closedAt: db.datetime({ optional: true }).description("Timestamp set when the order is closed"),
  };
};

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

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

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

export const transferOrder = createTransferOrderType({});
