# Part of Odoo. See LICENSE file for full copyright and licensing details.

import logging

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

_logger = logging.getLogger(__name__)


class SaleOrder(models.Model):
    _inherit = 'sale.order'

    clover_provider_enabled = fields.Boolean(
        string="Clover Provider Enabled",
        compute='_compute_clover_provider_enabled',
    )

    def _compute_clover_provider_enabled(self):
        provider = self.env['payment.provider'].sudo().search([
            ('code', '=', 'clover'),
            ('state', 'in', ('enabled', 'test')),
        ], limit=1)
        enabled = bool(provider)
        for order in self:
            order.clover_provider_enabled = enabled

    def action_clover_collect_payment(self):
        """Create an invoice (if needed) and open the Clover payment wizard."""
        self.ensure_one()

        if self.state not in ('sale', 'done'):
            raise UserError(
                _("You can only collect payment on confirmed orders.")
            )

        invoice = self.invoice_ids.filtered(
            lambda inv: inv.state == 'posted'
            and inv.payment_state in ('not_paid', 'partial')
            and inv.move_type == 'out_invoice'
        )[:1]

        if not invoice:
            draft_invoices = self.invoice_ids.filtered(
                lambda inv: inv.state == 'draft'
                and inv.move_type == 'out_invoice'
            )
            if draft_invoices:
                invoice = draft_invoices[0]
                invoice.action_post()
            else:
                invoices = self._create_invoices()
                if not invoices:
                    raise UserError(
                        _("Could not create an invoice for this order.")
                    )
                invoice = invoices[0]
                invoice.action_post()

        return {
            'name': _("Collect Clover Payment"),
            'type': 'ir.actions.act_window',
            'res_model': 'clover.payment.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'active_model': 'account.move',
                'active_id': invoice.id,
            },
        }
