<?php

namespace Modules\Bot\Http\Controllers;

use App\Models\User;
use App\Modules\Bot\Http\Interfaces\MessengerBotInterface;
use App\Modules\Bot\Models\UserBot;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class VkBot implements MessengerBotInterface
{
    private int $botId;
    private int $groupId;
    private string $groupConfirmation;

    public function __construct()
    {
        $this->botId = config('bot.vk_bot_id');
        $this->groupId = config('bot.vk_group_id');
        $this->groupConfirmation = config('bot.vk_group_confirmation');
    }

    public static function sendMessage(string $userBotId, string $message): void
    {   
        Log::info('Попытка отправить сообщение');
        $params['access_token'] = config('bot.vk_group_token');
        $params['v'] = '5.199';
        $params['random_id'] = random_int(1, PHP_INT_MAX);
        $params['user_id'] = $userBotId;
        $params['message'] = $message;

        $response =  Http::withoutVerifying()->withQueryParameters($params)->post("https://api.vk.com/method/messages.send");
    }

    public function allowMessages(Request $request)
    {
        if ($request->vkUserId and $request->naviomUserId and User::find($request->naviomUserId)) {
            UserBot::updateOrCreate(
                ['user_id' => $request->naviomUserId, 'bot_id' => $this->botId],
                ['user_bot_id' => $request->vkUserId]
            );
            $user = User::find($request->naviomUserId);
            $this->sendMessage($request->vkUserId, "Здравствуйте, {$user->name}! Вы успешно подписались на уведомления.");
        }
        return response()->json(['success' => true]);
    }

    public function handleVkCallback(Request $request)
    {
        switch ($request->type) {
            case 'confirmation':
                return $this->handleConfirmation($request->group_id);
            case 'message_deny':
                return $this->handleDenyMessage($request->object['user_id']);
        }
    }

    private function handleConfirmation(int $groupId): string
    {
        if ($groupId ==  $this->groupId) {
            return $this->groupConfirmation;
        }
    }

    private function handleDenyMessage(int $vkUserId): string
    {
        $subscription = UserBot::where('user_bot_id', $vkUserId)->where('bot_id', $this->botId)->first();
        if ($subscription) {
            $subscription->delete();
        }
        return 'ok';
    }
}
