import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import {
  businessPartner as businessPartnerStub,
  item as itemStub,
  unit as unitStub,
} from "../lib/_db_deps";
import { purchaseRequisition } from "./purchaseRequisition";

export interface CreatePurchaseRequisitionLineTypeParams<
  F extends Record<string, TailorAnyDBField>,
> {
  fields?: F;
  itemType: TailorAnyDBType;
  unitType: TailorAnyDBType;
  suggestedSupplierType: TailorAnyDBType;
}

export function createPurchaseRequisitionLineType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseRequisitionLineTypeParams<F>,
) {
  return db
    .type("PurchaseRequisitionLine", {
      purchaseRequisitionId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: purchaseRequisition },
          backward: "lines",
        })
        .description("Foreign key to PurchaseRequisition"),
      description: db.string().description("Line description (required, supports free-text)"),
      quantity: db.decimal().description("Requested quantity"),
      estimatedUnitPrice: db.decimal().description("Estimated unit price"),
      itemId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.itemType },
          backward: "purchaseRequisitionLines",
        })
        .description("Foreign key to Item"),
      unitId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.unitType },
          backward: "purchaseRequisitionLines",
        })
        .description("Unit of measure"),
      suggestedSupplierId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.suggestedSupplierType },
          backward: "purchaseRequisitionLines",
        })
        .description("Optional suggested supplier"),
      needByDate: db.date({ optional: true }).description("Optional need-by date for this line"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const purchaseRequisitionLine = createPurchaseRequisitionLineType({
  itemType: itemStub,
  unitType: unitStub,
  suggestedSupplierType: businessPartnerStub,
});
