import {
  ok,
  type ReadonlyDB,
  type PaginationInput,
  buildPaginatedResult,
  DEFAULT_PAGE_SIZE,
} from "@tailor-platform/erp-kit/module";
import type { TrialBalanceVariant } from "../generated/enums";
import type { DB } from "../generated/kysely-tailordb";

type TrialBalanceOrderByField = "generatedAt" | "variant" | "createdAt";

export interface ListTrialBalancesInput extends PaginationInput<TrialBalanceOrderByField> {
  companyId: string;
  accountingPeriodId?: string;
  variant?: string;
  fiscalYearId?: string;
}

/**
 * Function: listTrialBalances
 *
 * Lists trial balance headers for a company with optional filters for
 * accounting period, variant, and fiscal year. When fiscalYearId is provided,
 * a subquery finds accounting period IDs belonging to that fiscal year.
 */
export async function run(db: ReadonlyDB<DB>, input: ListTrialBalancesInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "generatedAt";
  const orderDirection = input.orderDirection ?? "desc";

  let query = db.selectFrom("TrialBalance").selectAll().where("companyId", "=", input.companyId);

  if (input.accountingPeriodId) {
    query = query.where("accountingPeriodId", "=", input.accountingPeriodId);
  }
  if (input.variant) {
    query = query.where("variant", "=", input.variant as TrialBalanceVariant);
  }
  if (input.fiscalYearId) {
    query = query.where(
      "accountingPeriodId",
      "in",
      db.selectFrom("AccountingPeriod").select("id").where("fiscalYearId", "=", input.fiscalYearId),
    );
  }

  const results = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  return ok(buildPaginatedResult(results, limit));
}
