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

type FiscalYearOrderByField = "startDate" | "endDate" | "name" | "createdAt";

export interface ListFiscalYearsInput extends PaginationInput<FiscalYearOrderByField> {
  companyId: string;
  startDate?: Date;
  endDate?: Date;
}

/**
 * Function: listFiscalYears
 *
 * Lists fiscal years for a company with optional date range filters.
 */
export async function run(db: ReadonlyDB<DB>, input: ListFiscalYearsInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "startDate";
  const orderDirection = input.orderDirection ?? "asc";

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

  if (input.startDate) {
    query = query.where("endDate", ">=", input.startDate);
  }
  if (input.endDate) {
    query = query.where("startDate", "<=", input.endDate);
  }

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

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