import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company as companyStub, user as userStub } from "../lib/_db_deps";

export const REQUISITION_STATUSES: [string, string, string, string, string, string] = [
  "DRAFT",
  "SUBMITTED",
  "APPROVED",
  "CONVERTED",
  "CANCELLED",
  "CLOSED",
];

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(REQUISITION_STATUSES).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(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

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