<?php

namespace App\Services\Tenant;

use App\Models\EventMediaAsset;
use App\Models\Tenant;

class TenantUsageService
{
    public function storageSummary(Tenant $tenant): array
    {
        $limitBytes = $this->storageLimitBytes($tenant);
        $usedBytes = $this->storageUsedBytes($tenant);
        $remainingBytes = $limitBytes !== null
            ? max(0, $limitBytes - $usedBytes)
            : null;

        return [
            'used_bytes' => $usedBytes,
            'limit_bytes' => $limitBytes,
            'remaining_bytes' => $remainingBytes,
            'used_mb' => $this->bytesToMegabytes($usedBytes),
            'limit_mb' => $limitBytes !== null ? $this->bytesToMegabytes($limitBytes) : null,
            'remaining_mb' => $remainingBytes !== null ? $this->bytesToMegabytes($remainingBytes) : null,
            'percentage' => $limitBytes !== null && $limitBytes > 0
                ? round(min(1, $usedBytes / $limitBytes) * 100, 1)
                : null,
        ];
    }

    public function storageLimitBytes(Tenant $tenant): ?int
    {
        $limitMb = $tenant->max_storage_mb;

        if ($limitMb === null) {
            return null;
        }

        $limitMb = (int) $limitMb;

        if ($limitMb <= 0) {
            return null;
        }

        return $limitMb * 1024 * 1024;
    }

    public function storageUsedBytes(Tenant $tenant): int
    {
        return (int) EventMediaAsset::query()
            ->whereHas('event', fn ($query) => $query->where('tenant_id', $tenant->getKey()))
            ->sum('size_bytes');
    }

    private function bytesToMegabytes(int $bytes): float
    {
        return round($bytes / (1024 * 1024), 2);
    }
}
