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

export const PURCHASE_ORDER_STATUSES: [
  string,
  string,
  string,
  string,
  string,
  string,
  string,
  string,
  string,
] = [
  "DRAFT",
  "SUBMITTED",
  "ORDERED",
  "PARTIALLY_RECEIVED",
  "RECEIVED",
  "PARTIALLY_BILLED",
  "BILLED",
  "CANCELLED",
  "CLOSED",
];

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

export function createPurchaseOrderType<const F extends Record<string, TailorAnyDBField>>(
  params: CreatePurchaseOrderTypeParams<F>,
) {
  return db
    .type("PurchaseOrder", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "purchaseOrders",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType ?? businessPartnerStub },
          backward: "purchaseOrders",
        })
        .description("Foreign key to supplier BusinessPartner"),
      documentReceivingSiteId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.siteType ?? siteStub },
          backward: "purchaseOrders",
        })
        .description("Optional document-level receiving Site"),
      paymentTermId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.paymentTermType ?? purchasePaymentTerm },
          backward: "purchaseOrders",
        })
        .description("Optional selected PurchasePaymentTerm"),
      status: db.enum(PURCHASE_ORDER_STATUSES).description("Purchase-order lifecycle status"),
      orderDate: db.date().description("Purchase-order document date"),
      externalSupplierOrderReference: db
        .string({ optional: true })
        .description("Optional external supplier order reference"),
      lines: db.string().description("Serialized purchase-order line collection"),
      paymentTermSnapshot: db
        .string({ optional: true })
        .description("Serialized immutable payment-term snapshot"),
      rejectionReason: db.string({ optional: true }).description("Latest rejection reason"),
      closeReason: db.string({ optional: true }).description("Close or write-off reason"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const purchaseOrder = createPurchaseOrderType({});
