# Copyright (C) 2021: Criptomart (<https://criptomart.net/>)
# @author: Criptomart (<tech@criptomart.net>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import logging

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError, Warning

_logger = logging.getLogger(__name__)

class AccountInvoice(models.Model):
     _inherit = 'account.invoice'

     @api.constrains('partner_id', 'partner_bank_id')
     def validate_partner_bank_id(self):
        for record in self:
            if record.partner_bank_id:
                if record.type in ('in_invoice', 'out_refund') and record.partner_bank_id.partner_id != record.partner_id.commercial_partner_id:
                    _logger.warning(_("Commercial partner and vendor account owners must be identical."))
                    record.partner_bank_id = False
                elif record.type in ('out_invoice', 'in_refund') and not record.company_id in record.partner_bank_id.partner_id.ref_company_ids:
                    raise ValidationError(_("The account selected for payment does not belong to the same company as this invoice."))

