# 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'

    poynt_transaction_count = fields.Integer(
        string="Poynt Transactions",
        compute='_compute_poynt_transaction_count',
    )

    def _compute_poynt_transaction_count(self):
        for order in self:
            order.poynt_transaction_count = self.env['payment.transaction'].sudo().search_count([
                ('sale_order_ids', 'in', order.id),
                ('provider_code', '=', 'poynt'),
            ])

    def action_view_poynt_transactions(self):
        self.ensure_one()
        transactions = self.env['payment.transaction'].sudo().search([
            ('sale_order_ids', 'in', self.id),
            ('provider_code', '=', 'poynt'),
        ])
        action = {
            'name': _("Poynt Transactions"),
            'type': 'ir.actions.act_window',
            'res_model': 'payment.transaction',
            'domain': [('id', 'in', transactions.ids)],
        }
        if len(transactions) == 1:
            action['view_mode'] = 'form'
            action['res_id'] = transactions.id
        else:
            action['view_mode'] = 'list,form'
        return action

    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,
            },
        }
