<?php

namespace App\Support;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

/**
 * 后台标准列表：`items` + `meta`（current_page / per_page / total / last_page）。
 * 供各 Admin Index 控制器复用，避免重复拼装分页 JSON。
 */
final class AdminApiList
{
    public const DEFAULT_PER_PAGE = 10;

    public const MAX_PER_PAGE = 100;

    /**
     * 读取 `page`、`per_page`，并夹在 [1, maxPerPage]。
     *
     * @return array{page: int, perPage: int}
     */
    public static function readPaging(Request $request, int $defaultPerPage = self::DEFAULT_PER_PAGE, int $maxPerPage = self::MAX_PER_PAGE): array
    {
        $perPage = min(max((int) $request->integer('per_page', $defaultPerPage), 1), $maxPerPage);
        $page = max((int) $request->integer('page', 1), 1);

        return ['page' => $page, 'perPage' => $perPage];
    }

    /**
     * @param  callable(object): array<string, mixed>  $row
     * @return array{items: list<array<string, mixed>>, meta: array{current_page: int, per_page: int, total: int, last_page: int}}
     */
    public static function payload(LengthAwarePaginator $paginator, callable $row): array
    {
        return [
            'items' => collect($paginator->items())->map($row)->values()->all(),
            'meta' => self::meta($paginator),
        ];
    }

    /**
     * @return array{current_page: int, per_page: int, total: int, last_page: int}
     */
    public static function meta(LengthAwarePaginator $paginator): array
    {
        return [
            'current_page' => $paginator->currentPage(),
            'per_page' => $paginator->perPage(),
            'total' => $paginator->total(),
            'last_page' => $paginator->lastPage(),
        ];
    }

    /**
     * @param  callable(object): array<string, mixed>  $row
     */
    public static function json(LengthAwarePaginator $paginator, callable $row): JsonResponse
    {
        return ApiResponse::success(self::payload($paginator, $row));
    }

    /**
     * 在标准列表外包一层字段（如 draw_id、job_no），与 items、meta 同级合并。
     *
     * @param  callable(object): array<string, mixed>  $row
     * @param  array<string, mixed>  $extra
     */
    public static function jsonWith(LengthAwarePaginator $paginator, callable $row, array $extra = []): JsonResponse
    {
        return ApiResponse::success(array_merge($extra, self::payload($paginator, $row)));
    }
}
