<?php

namespace Shm\ShmBlueprints\Auth;

use Shm\Shm;
use Shm\ShmUtils\I18n;
use Shm\ShmUtils\Response;

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

        return [
            'type' => Shm::boolean(),
            'description' => 'Установка телефона через Auth4App Passport',
            'args' => Shm::structure([
                'accessToken' => Shm::nonNull(Shm::string()),
            ]),
            'resolve' => function ($root, $args) {
                set_time_limit(60);

                $accessToken = $args['accessToken'];

                $options = [
                    'http' => [
                        'method' => 'POST',
                        'header' => "token: {$accessToken}\r\n",
                        'ignore_errors' => true,
                    ],
                ];

                $context = stream_context_create($options);
                $url = 'http://api.auth4app.com/auth/passport/response';

                $response = file_get_contents($url, false, $context);

                if ($response === false) {
                    Response::validation(I18n::get('auth_passport_error'));
                }

                $body = json_decode($response, true);

                if (!$body['phone']) {
                    Response::validation(I18n::get('auth_passport_error'));
                }

                $phone = (int) preg_replace("/[^,.0-9]/", '', $body['phone']);

                [$phoneField, $currentAuthStructure] = $this->validatePhoneSetRequest($phone);

                return $this->setPhoneForCurrentUser($phone, $phoneField, $currentAuthStructure);
            },
        ];
    }
}
