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

export const RECEIPT_STATUSES = ["NOT_RECEIVED", "PARTIALLY_RECEIVED", "RECEIVED"] as const;

export const BILLING_STATUSES = ["NOT_BILLED", "PARTIALLY_BILLED", "BILLED"] as const;

const builtins = (params: {
  companyType?: TailorAnyDBType;
  supplierType?: TailorAnyDBType;
  siteType?: TailorAnyDBType;
}) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const supplierId = db.uuid().description("Foreign key to supplier BusinessPartner");
  const receivingSiteId = db
    .uuid({ optional: true })
    .description("Default receiving Site for the order");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "purchaseOrders",
        })
      : companyId,
    supplierId: params.supplierType
      ? supplierId.relation({
          type: "n-1",
          toward: { type: params.supplierType },
          backward: "purchaseOrders",
        })
      : supplierId,
    receivingSiteId: params.siteType
      ? receivingSiteId.relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "purchaseOrders",
        })
      : receivingSiteId,
    orderStatus: db
      .enum(purchaseOrderLifecycle.states)
      .description("Purchase-order lifecycle status"),
    receiptStatus: db
      .enum(RECEIPT_STATUSES, { optional: true })
      .description("Receipt fulfillment status — set on approval"),
    billingStatus: db
      .enum(BILLING_STATUSES, { optional: true })
      .description("Billing fulfillment status — set on approval"),
    orderDate: db.date().description("Purchase-order document date"),
    externalSupplierOrderReference: db
      .string({ optional: true })
      .description("Optional external supplier order reference"),
    supplierSnapshotName: db
      .string({ optional: true })
      .description("Snapshotted supplier display name at order time"),
    rejectionReason: db.string({ optional: true }).description("Latest rejection reason"),
    closeReason: db.string({ optional: true }).description("Close or write-off reason"),
  };
};

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

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

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

export const purchaseOrder = createPurchaseOrderType({});
