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

const builtins = (params: { accountType?: TailorAnyDBType }) => {
  const accountId = db.uuid().description("Foreign key to posting Account");
  return {
    accountPayableDocumentLineId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: accountPayableDocumentLine },
        backward: "distributions",
      })
      .description("Foreign key to the commercial AP document line"),
    correctionOfDistributionLineId: db
      .uuid({ optional: true })
      .relation({
        type: "n-1",
        toward: { type: "self" },
        backward: "correctionDistributions",
      })
      .description("Optional self-reference to the posted AP distribution line being corrected"),
    accountId: params.accountType
      ? accountId.relation({
          type: "n-1",
          toward: { type: params.accountType },
          backward: "accountPayableDistributionLines",
        })
      : accountId,
    amount: db.decimal().description("Positive distribution amount"),
    description: db
      .string({ optional: true })
      .description("Optional distribution line description"),
  };
};

type ReservedFields = keyof ReturnType<typeof builtins> | CommonReservedFields;

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

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

export const accountPayableDistributionLine = createAccountPayableDistributionLineType({});
