<?php

declare(strict_types=1);

namespace App\Services\Uploads;

use App\DTOs\Uploads\UploadValidationResult;

final class UploadArchiveValidationService
{
    public function validate(string $path): UploadValidationResult
    {
        if (! is_file($path) || ! is_readable($path)) {
            return UploadValidationResult::fail('file_unreadable');
        }

        $size = (int) filesize($path);
        $maxBytes = (int) config('uploads.max_archive_size_mb', 0) * 1024 * 1024;
        if ($maxBytes > 0 && $size > $maxBytes) {
            return UploadValidationResult::fail('file_too_large', null, null, null, $size);
        }

        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mime = (string) ($finfo->file($path) ?: '');
        $allowed = array_values(array_unique((array) config('uploads.allowed_archive_mimes', [])));

        if ($mime === '' || ! in_array($mime, $allowed, true)) {
            return UploadValidationResult::fail('mime_not_allowed', null, null, $mime, $size);
        }

        return UploadValidationResult::ok(0, 0, $mime, $size);
    }
}