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

type JournalEntryOrderByField = "entryDate" | "status" | "createdAt";

export interface ListJournalEntriesInput extends PaginationInput<JournalEntryOrderByField> {
  companyId: string;
  accountingPeriodId?: string;
  status?: string;
  startDate?: Date;
  endDate?: Date;
}

/**
 * Function: listJournalEntries
 *
 * Lists journal entry headers for a company with optional filters for
 * accounting period, status, and date range.
 */
export async function run(db: ReadonlyDB<DB>, input: ListJournalEntriesInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "entryDate";
  const orderDirection = input.orderDirection ?? "desc";

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

  if (input.accountingPeriodId) {
    query = query.where("accountingPeriodId", "=", input.accountingPeriodId);
  }
  if (input.status) {
    query = query.where("status", "=", input.status as JournalEntryStatus);
  }
  if (input.startDate) {
    query = query.where("entryDate", ">=", input.startDate);
  }
  if (input.endDate) {
    query = query.where("entryDate", "<=", input.endDate);
  }

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

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