import {
  type CommonReservedFields,
  type NoReservedFields,
  defaultGqlPermission,
  defaultPermission,
} from "@tailor-platform/erp-kit/core";
import { db, type TailorAnyDBField } from "@tailor-platform/sdk";
import { accountPayableDocument } from "./accountPayableDocument";
import { accountPayableDocumentLine } from "./accountPayableDocumentLine";

export const ACCOUNT_PAYABLE_HOLD_REASON_CODES = [
  "INVOICE_UNIT_DIFFERS_FROM_PURCHASE_ORDER_UNIT",
  "INVOICE_UNIT_PRICE_DIFFERS_FROM_PURCHASE_ORDER_UNIT_PRICE",
  "INVOICE_QUANTITY_EXCEEDS_ORDERED_QUANTITY",
  "INVOICE_QUANTITY_EXCEEDS_RECEIVED_QUANTITY",
] as const;

export const ACCOUNT_PAYABLE_HOLD_SOURCES = ["SYSTEM", "MANUAL"] as const;

const builtins = {
  accountPayableDocumentId: db
    .uuid()
    .relation({
      type: "n-1",
      toward: { type: accountPayableDocument },
      backward: "holds",
    })
    .description("Foreign key to the held AccountPayableDocument"),
  accountPayableDocumentLineId: db
    .uuid({ optional: true })
    .relation({
      type: "n-1",
      toward: { type: accountPayableDocumentLine },
      backward: "holds",
    })
    .description(
      "Optional foreign key to the held AccountPayableDocumentLine; null is document scoped",
    ),
  reasonCode: db
    .enum(ACCOUNT_PAYABLE_HOLD_REASON_CODES)
    .description("Reason the payment hold was placed"),
  source: db
    .enum(ACCOUNT_PAYABLE_HOLD_SOURCES)
    .description("Whether the hold was produced by matching (SYSTEM) or placed by a user (MANUAL)"),
  releasedAt: db
    .datetime({ optional: true })
    .description("Timestamp when the hold was released; null while the hold is active"),
  releaseReason: db.string({ optional: true }).description("Optional reason recorded on release"),
};

type ReservedFields = keyof typeof builtins | CommonReservedFields;

export interface CreateAccountPayableDocumentHoldTypeParams<
  F extends Record<string, TailorAnyDBField>,
> {
  fields?: NoReservedFields<F, ReservedFields>;
}

export function createAccountPayableDocumentHoldType<
  const F extends Record<string, TailorAnyDBField>,
>(params: CreateAccountPayableDocumentHoldTypeParams<F> = {}) {
  return db
    .type("AccountPayableDocumentHold", {
      ...builtins,
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const accountPayableDocumentHold = createAccountPayableDocumentHoldType();
