import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { businessPartner as businessPartnerStub, company as companyStub } from "../lib/_db_deps";
import { goodsReceiptLifecycle } from "./goodsReceipt.lifecycle.generated";

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

export function createGoodsReceiptType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateGoodsReceiptTypeParams<F>,
) {
  return db
    .type("GoodsReceipt", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "goodsReceipts",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType },
          backward: "goodsReceipts",
        })
        .description("Foreign key to supplier BusinessPartner"),
      receiptDate: db.date().description("Receipt document date"),
      status: db.enum(goodsReceiptLifecycle.states).description("Goods-receipt lifecycle status"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const goodsReceipt = createGoodsReceiptType({
  companyType: companyStub,
  supplierType: businessPartnerStub,
});
