# Fusion Accounting - Payment Extensions
# Manual reconciliation and statement-line navigation for payments

import ast

from odoo import models, _


class FusionAccountPayment(models.Model):
    """Augments payments with manual reconciliation and the ability
    to navigate to matched bank statement lines."""

    _inherit = "account.payment"

    def action_open_manual_reconciliation_widget(self):
        """Open the manual reconciliation view, optionally filtered
        by the payment's partner and partner type.

        :return: An action dictionary for the reconciliation list.
        """
        self.ensure_one()
        act_vals = self.env['ir.actions.act_window']._for_xml_id(
            'fusion_accounting.action_move_line_posted_unreconciled'
        )
        if self.partner_id:
            ctx = ast.literal_eval(act_vals.get('context', '{}'))
            ctx['search_default_partner_id'] = self.partner_id.id
            if self.partner_type == 'customer':
                ctx['search_default_trade_receivable'] = 1
            elif self.partner_type == 'supplier':
                ctx['search_default_trade_payable'] = 1
            act_vals['context'] = ctx
        return act_vals

    def button_open_statement_lines(self):
        """Navigate to the bank reconciliation widget showing only
        the statement lines that are reconciled with this payment.

        :return: An action dictionary opening the reconciliation widget.
        """
        self.ensure_one()
        matched_lines = self.reconciled_statement_line_ids
        return self.env['account.bank.statement.line']._action_open_bank_reconciliation_widget(
            extra_domain=[('id', 'in', matched_lines.ids)],
            default_context={
                'create': False,
                'default_st_line_id': matched_lines.ids[-1],
            },
            name=_("Matched Transactions"),
        )
