import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { company as companyStub, user as userStub } from "../lib/_db_deps";
import { purchaseRequisitionLifecycle } from "./purchaseRequisition.lifecycle.generated";

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

export function createPurchaseRequisitionType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseRequisitionTypeParams<F>,
) {
  return db
    .type("PurchaseRequisition", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "purchaseRequisitions",
        })
        .description("Foreign key to Company"),
      requesterId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.userType },
          backward: "purchaseRequisitions",
        })
        .description("Foreign key to the user who created the requisition"),
      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"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseRequisition = createPurchaseRequisitionType({
  companyType: companyStub,
  userType: userStub,
});
