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 ORDER_STATUSES: [string, string, string, string, string] = [
  "DRAFT",
  "SUBMITTED",
  "ORDERED",
  "CANCELLED",
  "CLOSED",
];

export const RECEIPT_STATUSES: [string, string, string] = [
  "NOT_RECEIVED",
  "PARTIALLY_RECEIVED",
  "RECEIVED",
];

export const BILLING_STATUSES: [string, string, string] = [
  "NOT_BILLED",
  "PARTIALLY_BILLED",
  "BILLED",
];

export interface CreatePurchaseOrderTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType: TailorAnyDBType;
  supplierType: TailorAnyDBType;
  siteType: 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 },
          backward: "purchaseOrders",
        })
        .description("Foreign key to Company"),
      supplierId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.supplierType },
          backward: "purchaseOrders",
        })
        .description("Foreign key to supplier BusinessPartner"),
      documentReceivingSiteId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: params.siteType },
          backward: "purchaseOrders",
        })
        .description("Optional document-level receiving Site"),
      paymentTermId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: purchasePaymentTerm },
          backward: "purchaseOrders",
        })
        .description("Optional selected PurchasePaymentTerm"),
      orderStatus: db.enum(ORDER_STATUSES).description("Purchase-order lifecycle status"),
      receiptStatus: db
        .enum(RECEIPT_STATUSES, { optional: true })
        .description("Receipt fulfillment status — set on approval"),
      billingStatus: db
        .enum(BILLING_STATUSES, { optional: true })
        .description("Billing fulfillment status — set on approval"),
      orderDate: db.date().description("Purchase-order document date"),
      externalSupplierOrderReference: db
        .string({ optional: true })
        .description("Optional external supplier order reference"),
      supplierSnapshotName: db
        .string({ optional: true })
        .description("Snapshotted supplier display name at order time"),
      paymentTermSnapshotLines: db
        .object(
          {
            kind: db.string({ optional: true }),
            days: db.int({ optional: true }),
            fixedDayOfMonth: db.int({ optional: true }),
            percentage: db.decimal({ optional: true }),
            fixedAmount: db.decimal({ optional: true }),
            note: db.string({ optional: true }),
          },
          { optional: true, array: true },
        )
        .description("Snapshotted payment-term schedule lines at snapshot time"),
      currentRevisionNumber: db
        .int({ optional: true })
        .description("Current revision number, incremented on each change order application"),
      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({
  companyType: companyStub,
  supplierType: businessPartnerStub,
  siteType: siteStub,
});
