<?php

declare(strict_types=1);

namespace App\Services\Auth\Oauth;

use Illuminate\Support\Facades\Http;

class NaverProvider extends AbstractOauthProvider
{
    public function provider(): string
    {
        return 'naver';
    }

    public function authorizationUrl(string $state, ?string $nonce = null, ?string $redirectUri = null): string
    {
        $params = http_build_query([
            'client_id' => $this->config['client_id'] ?? env('NAVER_CLIENT_ID', ''),
            'redirect_uri' => $redirectUri ?? env('NAVER_REDIRECT_URL', ''),
            'response_type' => 'code',
            'state' => $state,
        ]);
        return 'https://nid.naver.com/oauth2.0/authorize?'.$params;
    }

    public function exchange(string $code, ?string $redirectUri = null): array
    {
        if ($this->isMock()) {
            return $this->mockProfile();
        }
        $tokenRes = Http::asForm()->post('https://nid.naver.com/oauth2.0/token', [
            'grant_type' => 'authorization_code',
            'client_id' => env('NAVER_CLIENT_ID'),
            'client_secret' => env('NAVER_CLIENT_SECRET'),
            'code' => $code,
        ])->throw()->json();

        $userRes = Http::withToken($tokenRes['access_token'])
            ->get('https://openapi.naver.com/v1/nid/me')
            ->throw()
            ->json();

        return [
            'id' => (string) ($userRes['response']['id'] ?? ''),
            'email' => $userRes['response']['email'] ?? null,
            'name' => $userRes['response']['name'] ?? null,
            'raw' => $userRes,
        ];
    }
}
