<?php

declare(strict_types=1);

namespace App\Services\Uploads;

use App\Repositories\Uploads\UploadSessionRepository;
use Carbon\CarbonImmutable;
use RuntimeException;

final class UploadQuotaService
{
    public function __construct(private readonly UploadSessionRepository $sessions)
    {
    }

    public function enforce(int $userId): void
    {
        $activeLimit = (int) config('uploads.quotas.max_active_sessions', 0);
        if ($activeLimit > 0) {
            $active = $this->sessions->countActiveForUser($userId);
            if ($active >= $activeLimit) {
                throw new RuntimeException('Upload limit reached.');
            }
        }

        $dailyLimit = (int) config('uploads.quotas.max_daily_sessions', 0);
        if ($dailyLimit > 0) {
            $since = CarbonImmutable::now()->startOfDay();
            $daily = $this->sessions->countForUserSince($userId, $since);
            if ($daily >= $dailyLimit) {
                throw new RuntimeException('Daily upload limit reached.');
            }
        }
    }
}
