package org.raddatz.familienarchiv.document;

import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.data.domain.Pageable;

import java.util.List;

public record DocumentSearchResult(
        @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
        List<DocumentSearchItem> items,
        @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
        long totalElements,
        @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
        int pageNumber,
        @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
        int pageSize,
        @Schema(requiredMode = Schema.RequiredMode.REQUIRED)
        int totalPages
) {
    /**
     * Single-page convenience factory used by empty-result shortcuts and by tests that
     * don't care about paging. Treats the whole list as page 0 of itself.
     */
    public static DocumentSearchResult of(List<DocumentSearchItem> items) {
        int size = items.size();
        return new DocumentSearchResult(items, size, 0, size, size == 0 ? 0 : 1);
    }

    /**
     * Paged factory used by the service when it has a real Pageable + full match count
     * (e.g. from Spring's Page<T> or from an in-memory sort-then-slice).
     */
    public static DocumentSearchResult paged(List<DocumentSearchItem> slice, Pageable pageable, long totalElements) {
        int pageSize = pageable.getPageSize();
        int totalPages = pageSize == 0 ? 0 : (int) ((totalElements + pageSize - 1) / pageSize);
        return new DocumentSearchResult(slice, totalElements, pageable.getPageNumber(), pageSize, totalPages);
    }
}
