<?php

namespace App\Services\Auth;

use App\Models\SystemEmailQuota;

class RegistrationEmailQuotaService
{
    public function isExceeded(): bool
    {
        $quota = $this->getCurrentPeriodQuota();

        return $quota->sent_count >= $quota->limit_count;
    }

    public function incrementSentCount(): void
    {
        $quota = $this->getCurrentPeriodQuota();
        $quota->sent_count = (int) $quota->sent_count + 1;
        $quota->updated_at = now();
        $quota->save();
    }

    private function getCurrentPeriodQuota(): SystemEmailQuota
    {
        $period = now()->format('Y-m');

        return SystemEmailQuota::query()->firstOrCreate(
            ['period' => $period],
            [
                'sent_count' => 0,
                'limit_count' => max(1, (int) config('registration.monthly_email_limit', 10000)),
                'updated_at' => now(),
            ]
        );
    }
}
