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

export const ACCOUNT_TYPES = ["ASSET", "LIABILITY", "EQUITY", "REVENUE", "EXPENSE"] as const;

const builtins = (params: { companyType?: TailorAnyDBType }) => {
  const companyId = db.uuid().description("Foreign key to Company from organization module");
  return {
    code: db.string().description("Structured numeric account code, unique within the company"),
    name: db.string().description("Descriptive name of the GL account"),
    accountType: db
      .enum(["ASSET", "LIABILITY", "EQUITY", "REVENUE", "EXPENSE"])
      .description("Account type: ASSET, LIABILITY, EQUITY, REVENUE, or EXPENSE"),
    companyId: params.companyType
      ? companyId.relation({
          type: "n-1",
          toward: { type: params.companyType },
          backward: "accounts",
        })
      : companyId,
    status: db.enum(accountLifecycle.states).description("Lifecycle status: ACTIVE or INACTIVE"),
  };
};

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

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

export function createAccountType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateAccountTypeParams<F>,
) {
  return db
    .type("Account", {
      ...builtins(params),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .indexes({
      fields: ["companyId", "code"],
      unique: true,
      name: "account_company_code_unique_idx",
    })
    .permission(defaultPermission)
    .gqlPermission(defaultGqlPermission);
}

export const account = createAccountType({});
