import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company as companyStub, currency as currencyStub } from "../lib/_db_deps";

export const BASE_COA_STATUSES = ["DRAFT", "ACTIVE", "ARCHIVED"] as const;

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

export function createChartOfAccountsType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateChartOfAccountsTypeParams<F>,
) {
  const statuses = [...BASE_COA_STATUSES, ...(params.additionalStatuses ?? [])] as [
    string,
    ...string[],
  ];

  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(statuses).description("Lifecycle status: DRAFT, ACTIVE, ARCHIVED"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const chartOfAccounts = createChartOfAccountsType({});
