# -*- coding: utf-8 -*-
"""
Block session-based information leaks and frontend detection mechanisms.
Specifically targets the web_enterprise module's subscription checks.
"""

import logging
from odoo import api, models

_logger = logging.getLogger(__name__)


class IrHttp(models.AbstractModel):
    """
    Override session info to prevent frontend from detecting license status.
    This specifically blocks web_enterprise's ExpirationPanel from showing.
    """
    _inherit = 'ir.http'

    def session_info(self):
        """
        Override session info to set permanent valid subscription data.
        This prevents the frontend ExpirationPanel from showing warnings.
        
        Key overrides:
        - expiration_date: Set to far future (2099)
        - expiration_reason: Set to 'renewal' (valid subscription)
        - warning: Set to False to hide all warning banners
        """
        result = super().session_info()
        
        # Override expiration-related session data
        # These are read by enterprise_subscription_service.js
        result['expiration_date'] = '2099-12-31 23:59:59'
        result['expiration_reason'] = 'renewal'
        result['warning'] = False  # Critical: prevents warning banners
        
        # Remove any "already linked" subscription info
        # These could trigger redirect prompts
        result.pop('already_linked_subscription_url', None)
        result.pop('already_linked_email', None)
        result.pop('already_linked_send_mail_url', None)
        
        _logger.debug("Session info patched - expiration set to 2099, warnings disabled")
        return result


class ResUsers(models.Model):
    """
    Override user creation/modification to prevent subscription checks.
    When users are created, Odoo Enterprise normally contacts Odoo servers
    to verify the subscription allows that many users.
    """
    _inherit = 'res.users'

    @api.model_create_multi
    def create(self, vals_list):
        """
        Override create to ensure no external subscription check is triggered.
        The actual check happens in publisher_warranty.contract which we've 
        already blocked, but this is an extra safety measure.
        """
        _logger.info("Creating %d user(s) - subscription check DISABLED", len(vals_list))
        
        # Create users normally - no external checks will happen
        # because publisher_warranty.contract.update_notification is blocked
        users = super().create(vals_list)
        
        # Don't trigger any warranty checks
        return users

    def write(self, vals):
        """
        Override write to log user modifications.
        """
        result = super().write(vals)
        
        # If internal user status changed, log it
        if 'share' in vals or 'groups_id' in vals:
            _logger.info("User permissions updated - subscription check DISABLED")
        
        return result
