# -*- coding: utf-8 -*-

from odoo import api, models, _
from odoo.exceptions import UserError
import logging

_logger = logging.getLogger(__name__)


class PortalWizardUser(models.TransientModel):
    """Override standard portal wizard to handle internal users with Fusion roles."""
    _inherit = 'portal.wizard.user'

    def action_grant_access(self):
        """Override: Handle Fusion portal roles when granting portal access.
        - Internal users with Fusion roles: assign backend groups, skip portal.
        - Portal users with Fusion roles: standard flow + assign role groups.
        """
        self.ensure_one()
        partner = self.partner_id

        # Check if the partner has any Fusion portal flags
        has_fusion_role = getattr(partner, 'is_technician_portal', False) or \
                          getattr(partner, 'is_authorizer', False) or \
                          getattr(partner, 'is_sales_rep_portal', False)

        # Find the linked user
        user = self.user_id
        if user and user._is_internal() and has_fusion_role:
            # Internal user with Fusion roles -- assign backend groups, no portal
            partner._assign_internal_role_groups(user)
            partner.authorizer_portal_user_id = user
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': _('Internal User Updated'),
                    'message': _('%s is an internal user. Backend permissions updated (no portal access needed).') % partner.name,
                    'type': 'info',
                    'sticky': True,
                }
            }

        # Standard Odoo portal flow (creates user, sends email, etc.)
        result = super().action_grant_access()

        # After standard flow, assign Fusion portal role groups
        if has_fusion_role:
            portal_user = self.user_id
            if not portal_user:
                # Fallback: find the user that was just created
                portal_user = self.env['res.users'].sudo().search([
                    ('partner_id', '=', partner.id),
                    ('share', '=', True),
                    ('active', '=', True),
                ], limit=1)
            if portal_user:
                partner._assign_portal_role_groups(portal_user)
                if not partner.authorizer_portal_user_id:
                    partner.authorizer_portal_user_id = portal_user
                _logger.info("Assigned Fusion portal role groups to user %s (partner: %s)",
                             portal_user.login, partner.name)

        return result


class ResUsers(models.Model):
    _inherit = 'res.users'

    def _generate_tutorial_articles(self):
        """Override to create custom welcome articles for internal staff
        instead of the default Odoo Knowledge onboarding article.
        """
        if 'knowledge.article' not in self.env:
            return super()._generate_tutorial_articles()

        for user in self:
            company = user.company_id or self.env.company
            render_ctx = {
                'user_name': user.name or 'Team Member',
                'company_name': company.name or 'Our Company',
                'company_email': company.email or '',
                'company_phone': company.phone or '',
            }

            try:
                body = self.env['ir.qweb']._render(
                    'fusion_authorizer_portal.welcome_article_internal',
                    render_ctx,
                    minimal_qcontext=True,
                    raise_if_not_found=False,
                )

                if not body:
                    _logger.warning("Internal staff welcome template not found, using default")
                    return super()._generate_tutorial_articles()

                self.env['knowledge.article'].sudo().create({
                    'name': f"Welcome {user.name} - {company.name}",
                    'icon': '🏢',
                    'body': body,
                    'internal_permission': 'none',
                    'is_article_visible_by_everyone': False,
                    'article_member_ids': [(0, 0, {
                        'partner_id': user.partner_id.id,
                        'permission': 'write',
                    })],
                    'favorite_ids': [(0, 0, {
                        'sequence': 0,
                        'user_id': user.id,
                    })],
                })

                _logger.info(f"Created custom welcome article for internal user {user.name}")

            except Exception as e:
                _logger.warning(f"Failed to create custom welcome article for {user.name}: {e}")
                # Fall back to default
                super(ResUsers, user)._generate_tutorial_articles()
