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

type UnassignedAccountOrderByField = "code" | "name" | "createdAt";

export interface ListUnassignedAccountsInput extends PaginationInput<UnassignedAccountOrderByField> {
  chartOfAccountsId: string;
}

/**
 * Function: listUnassignedAccounts
 *
 * Lists active accounts within a CoA that are not assigned to any account group.
 */
export async function run(db: ReadonlyDB<DB>, input: ListUnassignedAccountsInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "code";
  const orderDirection = input.orderDirection ?? "asc";

  const accounts = await db
    .selectFrom("Account")
    .selectAll()
    .where("chartOfAccountsId", "=", input.chartOfAccountsId)
    .where("accountGroupId", "is", null)
    .where("status", "=", "ACTIVE")
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

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