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

import logging

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

_logger = logging.getLogger(__name__)


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

    def action_poynt_collect_payment(self):
        """Create an invoice (if needed) and open the Poynt payment wizard.

        This shortcut lets staff collect payment directly from a confirmed
        sale order without manually creating and posting the invoice first.
        """
        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 Poynt Payment"),
            'type': 'ir.actions.act_window',
            'res_model': 'poynt.payment.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {
                'active_model': 'account.move',
                'active_id': invoice.id,
            },
        }
