"""
카카오 OAuth API 클라이언트
"""

import aiohttp

from config import kakao_settings


class KakaoOAuthClient:
    """카카오 OAuth API 클라이언트"""

    AUTH_URL = "https://kauth.kakao.com/oauth/authorize"
    TOKEN_URL = "https://kauth.kakao.com/oauth/token"
    USER_INFO_URL = "https://kapi.kakao.com/v2/user/me"

    def __init__(self):
        self.client_id = kakao_settings.KAKAO_CLIENT_ID
        self.client_secret = kakao_settings.KAKAO_CLIENT_SECRET
        self.redirect_uri = kakao_settings.KAKAO_REDIRECT_URI

    def get_authorization_url(self) -> str:
        """카카오 로그인 페이지 URL 반환"""
        return (
            f"{self.AUTH_URL}"
            f"?client_id={self.client_id}"
            f"&redirect_uri={self.redirect_uri}"
            f"&response_type=code"
        )

    async def get_access_token(self, code: str) -> dict:
        """인가 코드로 액세스 토큰 획득"""
        async with aiohttp.ClientSession() as session:
            data = {
                "grant_type": "authorization_code",
                "client_id": self.client_id,
                "client_secret": self.client_secret,
                "redirect_uri": self.redirect_uri,
                "code": code,
            }
            print(f"[kakao] Token request - client_id: {self.client_id}, redirect_uri: {self.redirect_uri}")
            async with session.post(self.TOKEN_URL, data=data) as response:
                result = await response.json()
                print(f"[kakao] Token response: {result}")
                return result

    async def get_user_info(self, access_token: str) -> dict:
        """액세스 토큰으로 사용자 정보 조회"""
        async with aiohttp.ClientSession() as session:
            headers = {"Authorization": f"Bearer {access_token}"}
            async with session.get(self.USER_INFO_URL, headers=headers) as response:
                return await response.json()


kakao_client = KakaoOAuthClient()
