<?php

declare(strict_types=1);

namespace App\Services\Auth\Oauth;

use Illuminate\Support\Facades\Http;

class KakaoProvider extends AbstractOauthProvider
{
    public function provider(): string
    {
        return 'kakao';
    }

    public function authorizationUrl(string $state, ?string $nonce = null, ?string $redirectUri = null): string
    {
        $params = http_build_query([
            'client_id' => $this->config['client_id'] ?? env('KAKAO_CLIENT_ID', ''),
            'redirect_uri' => $redirectUri ?? $this->config['redirect_url'] ?? env('KAKAO_REDIRECT_URL', ''),
            'response_type' => 'code',
            'state' => $state,
        ]);
        return 'https://kauth.kakao.com/oauth/authorize?'.$params;
    }

    public function exchange(string $code, ?string $redirectUri = null): array
    {
        if ($this->isMock()) {
            return $this->mockProfile();
        }
        $tokenRes = Http::asForm()->post('https://kauth.kakao.com/oauth/token', [
            'grant_type' => 'authorization_code',
            'client_id' => $this->config['client_id'] ?? env('KAKAO_CLIENT_ID'),
            'client_secret' => $this->config['client_secret'] ?? env('KAKAO_CLIENT_SECRET'),
            'redirect_uri' => $redirectUri ?? env('KAKAO_REDIRECT_URL'),
            'code' => $code,
        ])->throw()->json();

        $userRes = Http::withToken($tokenRes['access_token'])
            ->get('https://kapi.kakao.com/v2/user/me')
            ->throw()
            ->json();

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