# -*- coding: utf-8 -*-
from odoo import fields, models, api

class CrmLead(models.Model):
    """
    Inherited the CRM Lead model to add additional features.
    """
    _inherit = 'crm.lead'

    partner_id = fields.Many2one(
        'res.partner', string='Customer', index=True, tracking=10,
        domain="[('type', '!=', 'private'), ('company_id', 'in', (False, company_id)), ('state', '=', 'approve')]",
        help="Select the customer from the list of approved customers.")

    @api.model
    def create(self, vals):
        """Override create to ensure only approved contacts can be set"""
        if vals.get('partner_id'):
            partner = self.env['res.partner'].browse(vals['partner_id'])
            if partner.state != 'approve':
                vals['partner_id'] = False
        return super(CrmLead, self).create(vals)

    @api.onchange('partner_id')
    def _onchange_partner_id(self):
        """Ensure only approved contacts can be set"""
        if self.partner_id and self.partner_id.state != 'approve':
            self.partner_id = False
