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

const builtins = (params: { companyType?: TailorAnyDBType; userType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company");
  const requesterId = db.uuid().description("Foreign key to the user who created the requisition");
  return {
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "purchaseRequisitions",
        })
      : companyId,
    requesterId: params.userType
      ? requesterId.relation({
          type: "n-1",
          toward: { type: params.userType },
          backward: "purchaseRequisitions",
        })
      : requesterId,
    status: db
      .enum(purchaseRequisitionLifecycle.states)
      .description("Purchase-requisition lifecycle status"),
    justification: db
      .string({ optional: true })
      .description("Business justification for the requisition"),
    desiredDeliveryDate: db.date({ optional: true }).description("Optional desired delivery date"),
    rejectionReason: db.string({ optional: true }).description("Latest rejection reason"),
    closeReason: db.string({ optional: true }).description("Close reason when applicable"),
  };
};

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

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

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

export const purchaseRequisition = createPurchaseRequisitionType({});
