<?php
namespace EasyChat\Library\Support;









final class NextConversationSelector {

    




    public function select(array $rows, callable $capability_resolver): ?array {
        usort($rows, static function (array $left, array $right): int {
            $left_time = strtotime((string)($left['last_date'] ?? '')) ?: PHP_INT_MAX;
            $right_time = strtotime((string)($right['last_date'] ?? '')) ?: PHP_INT_MAX;

            if ($left_time === $right_time) {
                return (int)($left['chat_id'] ?? 0) <=> (int)($right['chat_id'] ?? 0);
            }

            return $left_time <=> $right_time;
        });

        foreach ($rows as $row) {
            if ((int)($row['chat_id'] ?? 0) <= 0
                || (int)($row['last_author'] ?? 0) !== 1
                || (int)($row['is_blocked'] ?? 0) === 1
                || trim((string)($row['last_date'] ?? '')) === '') {
                continue;
            }

            $capability = $capability_resolver($row);
            if (!is_array($capability) || empty($capability['can_reply'])) {
                continue;
            }

            return [
                'row' => $row,
                'reply_capability' => $capability,
            ];
        }

        return null;
    }
}
