# -*- coding: utf-8 -*-
# Copyright Solid Super Solutions (<https://solidsups.com>)
# License LGPL-3
from odoo import fields, models, _
from odoo.exceptions import UserError
from ast import literal_eval


class ResPartner(models.Model):
    """
        Inherited the Res partner model to add additional features.
            """
    _inherit = 'res.partner'

    state = fields.Selection([('draft', 'Draft'), ('approve', 'Approved'),
                              ("cancel", "Cancelled")], default='draft', help='Status of the contact',
                             tracking=True)

    approver_id = fields.Many2one(
        'res.users', string="Approved By", readonly=True,
        help='Person responsible for validating the contacts.')

    def action_approve_contact(self):
        """Manager validating the contacts."""
        if self.env.user.has_group(
                'sss_contact_approval.group_contacts_approval'):
            self.write({
                'state': "approve",
                'approver_id': self.env.uid
            })
        else:
            raise UserError(_(
                "You do not have the access right to Contacts Approval."
                " Please contact your administrator.")
            )

    def action_cancel_contact(self):
        """Manager cancelling the contacts."""
        if self.env.user.has_group(
                'sss_contact_approval.group_contacts_approval'):
            self.write({
                'state': "cancel",
                'approver_id': None
            })
        else:
            raise UserError(_(
                "You do not have the access right to Contacts Approval."
                " Please contact your administrator.")
            )

    def action_reset_contact(self):
        """Manager resetting the contacts."""
        if self.env.user.has_group(
                'sss_contact_approval.group_contacts_approval'):
            self.write({
                'state': "draft",
                'approver_id': None
            })
        else:
            raise UserError(_(
                "You do not have the access right to Contacts Approval."
                " Please contact your administrator.")
            )

    def action_view_sale_order(self):
        """Override the default sale order action to prevent setting draft contacts"""
        action = super(ResPartner, self).action_view_sale_order()
        # Only pass the partner_id in context if contact is approved
        if self.state != 'approve':
            if isinstance(action.get('context'), str):
                try:
                    ctx = dict(literal_eval(action['context']))
                except Exception:
                    ctx = {}
                ctx.update({
                    'active_id': self.id,
                    'active_ids': self.ids,
                    'active_model': 'res.partner'
                })
                if 'default_partner_id' in ctx:
                    del ctx['default_partner_id']
                action['context'] = ctx
            elif isinstance(action.get('context'), dict):
                if 'default_partner_id' in action['context']:
                    del action['context']['default_partner_id']
        return action

    def action_view_opportunity(self):
        """Override the default opportunity action to prevent setting draft contacts"""
        action = super(ResPartner, self).action_view_opportunity()
        # Only pass the partner_id in context if contact is approved
        if self.state != 'approve':
            if isinstance(action.get('context'), str):
                try:
                    ctx = dict(literal_eval(action['context']))
                except Exception:
                    ctx = {}
                # Remove any partner-related defaults from context
                ctx.update({
                    'active_id': self.id,
                    'active_ids': self.ids,
                    'active_model': 'res.partner',
                    'default_partner_id': False,  # Explicitly set to False
                    'search_default_partner_id': False
                })
                action['context'] = ctx
            elif isinstance(action.get('context'), dict):
                action['context'].update({
                    'default_partner_id': False,  # Explicitly set to False
                    'search_default_partner_id': False
                })
        return action
