<?php

namespace Shm\ShmBlueprints\Auth;

use Shm\Shm;
use Shm\ShmUtils\Config;

class ShmMsgAuth extends ShmAuthBase
{
    public function make(): array
    {
        if (count($this->_authStructures) === 0) {
            throw new \Exception("No auth structures defined for Msg Auth");
        }

        return [
            'type' => Shm::structure([
                'auth' => Shm::boolean(),
                'token' => Shm::string(),
                'code' => Shm::int(),
                'qrLink' => Shm::string(),
                'code_id' => Shm::string(),
                'links' => Shm::arrayOf(
                    Shm::structure([
                        'title' => Shm::string(),
                        'action' => Shm::enum(['sendMessage', 'makeCall']),
                        'contact' => Shm::string(),
                        'link' => Shm::string(),
                        'image' => Shm::string(),
                        'color' => Shm::string(),
                    ])->staticBaseTypeName('ShmMsgAuthLink')
                ),
                'otherLinks' => Shm::arrayOf(
                    Shm::structure([
                        'title' => Shm::string(),
                        'action' => Shm::enum(['sendMessage', 'makeCall']),
                        'contact' => Shm::string(),
                        'link' => Shm::string(),
                        'image' => Shm::string(),
                        'color' => Shm::string(),
                    ])->staticBaseTypeName('ShmMsgAuthLink')
                ),
            ])->staticBaseTypeName('ShmMsgAuth'),
            'description' => 'Авторизация через Месенджеры',
            'args' => Shm::structure([
                'phone' => Shm::nonNull(Shm::string()),
                'code_id' => Shm::string(),
                'deviceInfo' => $this->deviceInfoStructure(),
            ]),
            'resolve' => function ($root, $args) {
                if (isset($args['code_id']) && $args['code_id']) {
                    $context = stream_context_create([
                        'ssl' => [
                            'verify_peer' => false,
                            'verify_peer_name' => false,
                        ],
                    ]);

                    $auth4appApiKey = Config::get('auth4app', "a4d5b3fa5dc37d3590deda42cd17513ede4ee3dec9fe2ee71bac94f58d817f7c");

                    $result = json_decode(file_get_contents(
                        "http://api.auth4app.com/code/result?code_id=" . $args['code_id'] . "&api_key=" . $auth4appApiKey,
                        false,
                        $context
                    ), true);

                    if ($result['auth'] == true) {
                        $phone = (int) preg_replace("/[^,.0-9]/", '', $args['phone']);

                        $findAuthUserAndStructure = $this->findAuthUserAndStructure(Shm::phone(), (int) $phone, []);

                        if (!$findAuthUserAndStructure) {
                            $regNewUser = $this->regNewUser(Shm::phone(), (int) $phone, []);

                            [$user, $regStructure] = $regNewUser;

                            return [
                                'token' => $this->authToken($regStructure, $user->_id, $args),
                                'auth' => true,
                            ];
                        }

                        [$user, $userStructure] = $findAuthUserAndStructure;

                        return [
                            'token' => $this->authToken($userStructure, $user->_id, $args),
                            'auth' => true,
                        ];
                    }
                } else {
                    $phone = (int) preg_replace("/[^,.0-9]/", '', $args['phone']);

                    $context = stream_context_create([
                        'ssl' => [
                            'verify_peer' => false,
                            'verify_peer_name' => false,
                        ],
                    ]);

                    $auth4appApiKey = Config::get('auth4app', "a4d5b3fa5dc37d3590deda42cd17513ede4ee3dec9fe2ee71bac94f58d817f7c");

                    $result = json_decode(file_get_contents(
                        "http://api.auth4app.com/code/get?phone=$phone&api_key=" . $auth4appApiKey,
                        false,
                        $context
                    ), true);

                    return $result;
                }
            },
        ];
    }
}
