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

from odoo import api, fields, models
import logging

_logger = logging.getLogger(__name__)


class ResConfigSettings(models.TransientModel):
    _inherit = 'res.config.settings'

    ff_ringcentral_enabled = fields.Boolean(
        string='Enable RingCentral Faxing',
        config_parameter='fusion_faxes.ringcentral_enabled',
    )
    ff_ringcentral_server_url = fields.Char(
        string='RingCentral Server URL',
        config_parameter='fusion_faxes.ringcentral_server_url',
        default='https://platform.ringcentral.com',
    )
    ff_ringcentral_client_id = fields.Char(
        string='Client ID',
        config_parameter='fusion_faxes.ringcentral_client_id',
        groups='fusion_faxes.group_fax_manager',
    )
    ff_ringcentral_client_secret = fields.Char(
        string='Client Secret',
        config_parameter='fusion_faxes.ringcentral_client_secret',
        groups='fusion_faxes.group_fax_manager',
    )
    ff_ringcentral_jwt_token = fields.Char(
        string='JWT Token',
        config_parameter='fusion_faxes.ringcentral_jwt_token',
        groups='fusion_faxes.group_fax_manager',
    )

    def action_test_ringcentral_connection(self):
        """Test connection to RingCentral using stored credentials."""
        self.ensure_one()
        ICP = self.env['ir.config_parameter'].sudo()
        client_id = ICP.get_param('fusion_faxes.ringcentral_client_id', '')
        client_secret = ICP.get_param('fusion_faxes.ringcentral_client_secret', '')
        server_url = ICP.get_param('fusion_faxes.ringcentral_server_url', 'https://platform.ringcentral.com')
        jwt_token = ICP.get_param('fusion_faxes.ringcentral_jwt_token', '')

        if not all([client_id, client_secret, jwt_token]):
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': 'Configuration Missing',
                    'message': 'Please fill in Client ID, Client Secret, and JWT Token before testing.',
                    'type': 'warning',
                    'sticky': False,
                },
            }

        try:
            from ringcentral import SDK
            sdk = SDK(client_id, client_secret, server_url)
            platform = sdk.platform()
            platform.login(jwt=jwt_token)

            # Fetch account info to verify
            res = platform.get('/restapi/v1.0/account/~/extension/~')
            ext_info = res.json()
            ext_name = ext_info.name if hasattr(ext_info, 'name') else str(ext_info.get('name', 'Unknown'))

            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': 'Connection Successful',
                    'message': f'Connected to RingCentral as: {ext_name}',
                    'type': 'success',
                    'sticky': False,
                },
            }
        except ImportError:
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': 'SDK Not Installed',
                    'message': 'The ringcentral Python package is not installed. Run: pip install ringcentral',
                    'type': 'danger',
                    'sticky': True,
                },
            }
        except Exception as e:
            _logger.exception("RingCentral connection test failed")
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': 'Connection Failed',
                    'message': str(e),
                    'type': 'danger',
                    'sticky': True,
                },
            }

    def set_values(self):
        """Protect credential fields from being blanked accidentally."""
        protected_keys = [
            'fusion_faxes.ringcentral_client_id',
            'fusion_faxes.ringcentral_client_secret',
            'fusion_faxes.ringcentral_jwt_token',
        ]
        ICP = self.env['ir.config_parameter'].sudo()
        for key in protected_keys:
            field_map = {
                'fusion_faxes.ringcentral_client_id': 'ff_ringcentral_client_id',
                'fusion_faxes.ringcentral_client_secret': 'ff_ringcentral_client_secret',
                'fusion_faxes.ringcentral_jwt_token': 'ff_ringcentral_jwt_token',
            }
            field_name = field_map[key]
            new_val = getattr(self, field_name, None)
            if new_val in (None, False, ''):
                existing = ICP.get_param(key, '')
                if existing:
                    ICP.set_param(key, existing)
        return super().set_values()
