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

type FinancialStatementOrderByField = "createdAt" | "statementType" | "status" | "generatedAt";

export interface ListFinancialStatementsInput extends PaginationInput<FinancialStatementOrderByField> {
  companyId: string;
  statementType?: string;
  status?: string;
  startDate?: Date;
  endDate?: Date;
}

/**
 * Function: listFinancialStatements
 *
 * Lists financial statement headers for a company with optional filters
 * for statement type, status, and date range (by reportingDate).
 */
export async function run(db: ReadonlyDB<DB>, input: ListFinancialStatementsInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "createdAt";
  const orderDirection = input.orderDirection ?? "desc";

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

  if (input.statementType) {
    query = query.where(
      "statementType",
      "=",
      input.statementType as FinancialStatementStatementType,
    );
  }
  if (input.status) {
    query = query.where("status", "=", input.status as FinancialStatementStatus);
  }
  if (input.startDate) {
    query = query.where("reportingDate", ">=", input.startDate);
  }
  if (input.endDate) {
    query = query.where("reportingDate", "<=", input.endDate);
  }

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

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