import { db, type TailorAnyDBField, type TailorAnyDBType } from "@tailor-platform/sdk";
import { defaultGqlPermission, defaultPermission } from "../../../shared/modelPermissions";
import { company as companyStub, currency as currencyStub } from "../lib/_db_deps";
import { chartOfAccountsLifecycle } from "./chartOfAccounts.lifecycle.generated";

export interface CreateChartOfAccountsTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  currencyType?: TailorAnyDBType;
}

export function createChartOfAccountsType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateChartOfAccountsTypeParams<F>,
) {
  return db
    .type(["ChartOfAccounts", "ChartsOfAccounts"], {
      name: db.string().description("Name of the chart of accounts"),
      description: db.string({ optional: true }).description("Optional description of the CoA"),
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "chartOfAccounts",
        })
        .description("Foreign key to Company from organization module"),
      baseCurrencyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.currencyType ?? currencyStub },
          backward: "chartsOfAccounts",
        })
        .description("Base currency inherited from the parent company at creation time"),
      status: db
        .enum(chartOfAccountsLifecycle.states)
        .description("Lifecycle status: DRAFT, ACTIVE, ARCHIVED"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const chartOfAccounts = createChartOfAccountsType({});
