<?php

namespace App\Services\Storage;

use App\Models\MediaStorageTarget;

class StorageHealthService
{
    public function getCapacity(MediaStorageTarget $target): array
    {
        $monitorPath = $target->config['monitor_path'] ?? $target->config['root'] ?? null;

        if (! $monitorPath || ! file_exists($monitorPath)) {
            return [
                'status' => 'unknown',
                'total' => null,
                'free' => null,
                'used' => null,
                'percentage' => null,
                'path' => $monitorPath,
            ];
        }

        try {
            $total = @disk_total_space($monitorPath);
            $free = @disk_free_space($monitorPath);

            if ($total === false || $free === false) {
                return [
                    'status' => 'unavailable',
                    'total' => null,
                    'free' => null,
                    'used' => null,
                    'percentage' => null,
                    'path' => $monitorPath,
                ];
            }

            $used = $total - $free;
            $percentage = $total > 0 ? round(($used / $total) * 100, 1) : null;

            return [
                'status' => 'ok',
                'total' => $total,
                'free' => $free,
                'used' => $used,
                'percentage' => $percentage,
                'path' => $monitorPath,
            ];
        } catch (\Throwable $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage(),
                'total' => null,
                'free' => null,
                'used' => null,
                'percentage' => null,
                'path' => $monitorPath,
            ];
        }
    }
}

