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

export const GOODS_RECEIPT_STATUSES: [string, string, string] = ["DRAFT", "POSTED", "CANCELLED"];

export interface CreateGoodsReceiptTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  supplierType?: TailorAnyDBType;
  purchaseOrderType?: 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 ?? companyStub },
          backward: "goodsReceipts",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType ?? businessPartnerStub },
          backward: "goodsReceipts",
        })
        .description("Foreign key to supplier BusinessPartner"),
      purchaseOrderId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.purchaseOrderType ?? purchaseOrder },
          backward: "goodsReceipts",
        })
        .description("Foreign key to PurchaseOrder"),
      receiptDate: db.date().description("Receipt document date"),
      status: db.enum(GOODS_RECEIPT_STATUSES).description("Goods-receipt lifecycle status"),
      lines: db.string().description("Serialized receipt-line collection"),
      inventoryHandoff: db
        .string({ optional: true })
        .description("Serialized inbound inventory handoff payload"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const goodsReceipt = createGoodsReceiptType({});
