<?php

namespace App\Http\Traits;

use App\Models\ApiBlockedIp;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

trait UnauthenticatedApiIpTrait
{
    
    /** This Trait is to manage the unauthenticated API IP addresses.
    * Whene ever an unauthenticated IP made a API request, 
    * it will be noted and after 3 unauthenticated attempts it will be blocked.
    **/
    


    /**
     * Adds an unauthorized attempt for the given IP address.
     *
     * @param string $ip The IP address to add the attempt for.
     * @throws \Exception If there is an error while saving the record.
     */
    public function addUnauthAttempt($ip)
    {
        // Define the maximum number of attempts before blocking
        $maxAttempts = 3;

        $existingRecord = ApiBlockedIp::firstOrNew(['ip' => $ip]);

        // Increment the 'attempts' column
        $existingRecord->increment('attempts');
        $existingRecord->increment('total_attempts');

        // Check if attempts >= maxAttempts and blocked_at is null
        if ($existingRecord->attempts >= $maxAttempts && $existingRecord->blocked_at == null) {
            // Update 'blocked_at' with the current date and time
            $existingRecord->blocked_at = Carbon::now();
        }

        $existingRecord->save();
    }


    /**
     * Checks if the given IP address is blocked.
     *
     * @param string $ip The IP address to check.
     * @return bool True if the IP address is blocked, false otherwise.
     */
    public function checkIsIpBlocked($ip)
    {
        $existingRecord = ApiBlockedIp::where('ip', $ip)
            ->whereNotNull('blocked_at')->select('id')->first();

        if ($existingRecord) {
            return true;
        }

        return false;
    }

    
}
