# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

import json
import logging

from odoo import http
from odoo.http import request

_logger = logging.getLogger(__name__)


class RcOAuthController(http.Controller):

    @http.route('/ringcentral/oauth', type='http', auth='user', website=False)
    def oauth_callback(self, code=None, state=None, error=None, **kw):
        """Handle the OAuth redirect from RingCentral after user authorizes."""
        if error:
            _logger.error("RingCentral OAuth error: %s", error)
            return request.redirect('/odoo?rc_error=oauth_denied')

        if not code:
            return request.redirect('/odoo?rc_error=no_code')

        config_id = None
        if state:
            try:
                state_data = json.loads(state)
                config_id = state_data.get('config_id')
            except (json.JSONDecodeError, TypeError):
                pass

        if not config_id:
            configs = request.env['rc.config'].search([], limit=1)
            if not configs:
                return request.redirect('/odoo?rc_error=no_config')
            config_id = configs.id

        config = request.env['rc.config'].browse(config_id)
        if not config.exists():
            return request.redirect('/odoo?rc_error=invalid_config')

        base_url = request.env['ir.config_parameter'].sudo().get_param('web.base.url', '')
        redirect_uri = f'{base_url}/ringcentral/oauth'

        success = config.exchange_auth_code(code, redirect_uri)
        if success:
            return request.redirect(f'/odoo/rc-config/{config_id}')
        else:
            return request.redirect(f'/odoo/rc-config/{config_id}?rc_error=token_exchange_failed')
