<?php
declare(strict_types=1);

namespace App\Services;

final class BackupInventoryService
{
    /** @return array<string,mixed> */
    public function report(int $limit = 8): array
    {
        $directories = [
            BASE_PATH . '/storage/backups',
            BASE_PATH . '/storage/updates/backups',
        ];
        $items = [];
        $totalBytes = 0;

        foreach ($directories as $directory) {
            if (!is_dir($directory)) {
                continue;
            }
            $iterator = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS),
                \RecursiveIteratorIterator::SELF_FIRST
            );
            foreach ($iterator as $entry) {
                if (!$entry->isFile()) {
                    continue;
                }
                $size = (int)$entry->getSize();
                $totalBytes += $size;
                $items[] = [
                    'name' => $entry->getFilename(),
                    'path' => str_replace('\\', '/', substr($entry->getPathname(), strlen(BASE_PATH) + 1)),
                    'size' => $size,
                    'modified_at' => date('Y-m-d H:i:s', (int)$entry->getMTime()),
                    'timestamp' => (int)$entry->getMTime(),
                ];
            }
        }

        usort($items, static fn(array $a, array $b): int => $b['timestamp'] <=> $a['timestamp']);
        $latest = array_slice($items, 0, max(1, $limit));

        return [
            'status' => $items === [] ? 'warning' : 'ok',
            'count' => count($items),
            'total_bytes' => $totalBytes,
            'latest' => $latest,
            'message' => $items === [] ? 'Aucune sauvegarde détectée.' : count($items) . ' fichier(s) de sauvegarde détecté(s).',
        ];
    }
}
