<?php

namespace App\Socialite;

use GuzzleHttp\RequestOptions;
use Laravel\Socialite\Two\AbstractProvider;
use Laravel\Socialite\Two\User;

class ChurchToolsProvider extends AbstractProvider
{
    protected $scopes = ['openid', 'email', 'profile'];

    protected $scopeSeparator = ' ';

    protected function getBaseUrl(): string
    {
        return rtrim(config('services.churchtools.url'), '/');
    }

    protected function getAuthUrl($state): string
    {
        return $this->buildAuthUrlFromBase(
            $this->getBaseUrl().'/oauth/authorize',
            $state,
        );
    }

    protected function getTokenUrl(): string
    {
        return $this->getBaseUrl().'/oauth/access_token';
    }

    /**
     * @param  string  $token
     * @return array<string, mixed>
     */
    protected function getUserByToken($token): array
    {
        $response = $this->getHttpClient()->get(
            $this->getBaseUrl().'/oauth/userinfo',
            [
                RequestOptions::HEADERS => [
                    'Authorization' => 'Bearer '.$token,
                    'Accept' => 'application/json',
                ],
            ],
        );

        return json_decode((string) $response->getBody(), true);
    }

    protected function mapUserToObject(array $user): User
    {
        return (new User)->setRaw($user)->map([
            'id' => $user['id'] ?? null,
            'name' => $user['displayName'] ?? trim(($user['firstName'] ?? '').' '.($user['lastName'] ?? '')),
            'email' => $user['email'] ?? null,
            'avatar' => $user['imageUrl'] ?? null,
        ]);
    }
}
