import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { chartOfAccounts as chartOfAccountsStub } from "./chartOfAccounts";

export interface CreateAccountGroupTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  chartOfAccountsType?: TailorAnyDBType;
}

export function createAccountGroupType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateAccountGroupTypeParams<F>,
) {
  return db
    .type("AccountGroup", {
      code: db.string().description("Unique group code within the CoA"),
      name: db.string().description("Display name of the account group"),
      chartOfAccountsId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.chartOfAccountsType ?? chartOfAccountsStub },
          backward: "accountGroups",
        })
        .description("Foreign key to the parent ChartOfAccounts"),
      parentAccountGroupId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: "self" },
          backward: "childAccountGroups",
        })
        .description("Optional parent group for hierarchical nesting"),
      sortOrder: db.int({ optional: true }).description("Display sequence among sibling groups"),
      numberRangeStart: db
        .int({ optional: true })
        .description("Start of the allowed account number range (inclusive)"),
      numberRangeEnd: db
        .int({ optional: true })
        .description("End of the allowed account number range (inclusive)"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["chartOfAccountsId", "code"],
      unique: true,
      name: "account_group_coa_code_unique_idx",
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const accountGroup = createAccountGroupType({});
