<?php

namespace App\Support\Lists;

use Illuminate\Http\Request;

/**
 * Normalized query-string list state shared by index pages.
 *
 * @phpstan-type ListState array{
 *   q: string,
 *   sort: string|null,
 *   dir: string|null,
 *   per_page: int,
 *   filters: array<string, mixed>
 * }
 */
final class ListState
{
    /**
     * @param  list<string>  $filterKeys
     * @return ListState
     */
    public static function from(Request $request, array $filterKeys = []): array
    {
        $filters = [];
        foreach ($filterKeys as $key) {
            $value = $request->input($key);
            if ($value !== null && $value !== '') {
                $filters[$key] = $value;
            }
        }

        $sort = $request->input('sort');
        $dir = $request->input('dir');

        return [
            'q' => trim((string) $request->input('q', '')),
            'sort' => is_string($sort) && $sort !== '' ? $sort : null,
            'dir' => is_string($dir) && in_array(strtolower($dir), ['asc', 'desc'], true) ? strtolower($dir) : null,
            'per_page' => ListQuery::perPage($request),
            'filters' => $filters,
        ];
    }

    public static function hasActiveFilters(Request $request, array $keys = ['q', 'sort', 'dir', 'per_page']): bool
    {
        foreach ($keys as $key) {
            $value = $request->query($key);
            if ($value !== null && $value !== '' && ! ($key === 'per_page' && (int) $value === ListQuery::DEFAULT_PER_PAGE)) {
                return true;
            }
        }

        return false;
    }
}
