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

const builtins = (params: { accountType?: TailorAnyDBType }) => {
  const accountId = db.uuid().description("Foreign key to Account (coa-management)");
  return {
    journalEntryId: db
      .uuid()
      .relation({
        type: "n-1",
        toward: { type: journalEntry },
        backward: "lines",
      })
      .description("Foreign key to JournalEntry"),
    accountId: params.accountType
      ? accountId.relation({
          type: "n-1",
          toward: { type: params.accountType },
          backward: "journalLines",
        })
      : accountId,
    debitAmount: db
      .decimal({ optional: true })
      .description("Debit amount (mutually exclusive with creditAmount)"),
    creditAmount: db
      .decimal({ optional: true })
      .description("Credit amount (mutually exclusive with debitAmount)"),
    description: db.string({ optional: true }).description("Optional line-level description"),
  };
};

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

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

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

export const journalLine = createJournalLineType({});
