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

type AccountOrderByField = "code" | "name" | "accountType" | "status" | "createdAt";

export interface ListAccountsInput extends PaginationInput<AccountOrderByField> {
  companyId: string;
  accountIds?: string[];
  accountType?: AccountAccountType;
  status?: AccountStatus;
}

/**
 * Function: listAccounts
 *
 * Lists company accounts with optional filters for type and status.
 */
export async function run(db: ReadonlyDB<DB>, input: ListAccountsInput) {
  const limit = input.limit ?? input.accountIds?.length ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "code";
  const orderDirection = input.orderDirection ?? "asc";

  if (input.accountIds && input.accountIds.length === 0) {
    return ok(buildPaginatedResult([], limit));
  }

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

  if (input.accountIds && input.accountIds.length > 0) {
    query = query.where("id", "in", input.accountIds);
  }
  if (input.accountType) {
    query = query.where("accountType", "=", input.accountType);
  }
  if (input.status) {
    query = query.where("status", "=", input.status);
  }

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

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