<?php

declare(strict_types=1);

namespace App\Services\Uploads;

use App\Repositories\Uploads\UploadSessionRepository;
use Illuminate\Support\Facades\File;

final class UploadStatusService
{
    public function __construct(
        private readonly UploadSessionRepository $sessions,
        private readonly UploadStorageService $storage
    )
    {
    }

    public function get(string $sessionId): array
    {
        $session = $this->sessions->getOrFail($sessionId);
        $receivedBytes = $this->safeFileSize($session->tempPath);

        return [
            'session_id' => $session->id,
            'status' => $session->status,
            'progress' => $session->progress,
            'failure_reason' => $session->failureReason,
            'user_id' => $session->userId,
            'received_bytes' => $receivedBytes,
        ];
    }

    private function safeFileSize(string $path): int
    {
        $tmpRoot = $this->storage->sectionPath('tmp');
        $realRoot = realpath($tmpRoot);
        $realPath = realpath($path);

        if (! $realRoot || ! $realPath || strpos($realPath, $realRoot) !== 0) {
            return 0;
        }

        if (! File::exists($realPath)) {
            return 0;
        }

        return (int) File::size($realPath);
    }
}
