import logging

from requests import Response
from typing import Optional

from .base import BaseClient
from watcher.config import settings

logger = logging.getLogger(__name__)


class JnsClient(BaseClient):

    TVM2_CLIENT = 'jns'
    HOST = settings.JNS_API_HOST

    def _raise_for_status(self, response: Response) -> None:
        if response.status_code == 409 and response.json()['code'] == 6:
            logger.warning('Already sent message with same request_id')
            return
        elif response.status_code == 400 and response.json()['code'] == 3:
            logger.warning('No such user found (fired maybe?)')
            return
        super()._raise_for_status(response=response)

    def send_message(
        self, template: str, login: str,
        channel: str, params: Optional[dict] = None,
        request_id: Optional[str] = None
    ):
        logger.info(
            f'Sending message for: {login}, '
            f'template: {template}'
        )
        data = {
            'project': settings.JNS_PROJECT,
            'template': template,
            'recipient': {
                channel: {
                    'internal': [
                        {'login': login}
                    ]
                }
            }
        }
        if params:
            data['params'] = params
        if request_id:
            data['request_id'] = request_id
        return self._make_request(
            path='api/messages/send',
            method='post',
            data=data,
        )

    def upsert_user(self, login: str, chat_id: int) -> None:
        logger.info(f'Upserting user: {login}')
        self._make_request(
            path='api/telegram/users/upsert',
            method='post',
            data={
                'bot': settings.BOT_KEY,
                'users': [
                    {
                        'name': login,
                        'chat_id': chat_id,
                    }
                ]
            }
        )

    def delete_users(self, logins: list[str]) -> None:
        logger.info(f'Deleting users: {logins}')
        self._make_request(
            path='api/telegram/users/delete',
            method='post',
            data={
                'bot': settings.BOT_KEY,
                'names': logins
            }
        )


jns_client = JnsClient()
