# Fusion Accounting - Mail Activity Extensions
# Tax report activity actions with closing-parameter support

from odoo import fields, models, _


class FusionMailActivity(models.Model):
    """Extends mail activities with tax-closing context so that
    opening the activity navigates to the correct tax report period."""

    _inherit = "mail.activity"

    account_tax_closing_params = fields.Json(
        string="Tax closing additional params",
    )

    def action_open_tax_activity(self):
        """Navigate to either the tax-to-pay wizard (for tax-payment
        activities) or the generic tax report (for periodic reminders),
        using the stored closing parameters to set the report period."""
        self.ensure_one()

        # Tax payment activity → open the payment wizard
        tax_pay_type = self.env.ref(
            'fusion_accounting.mail_activity_type_tax_report_to_pay'
        )
        if self.activity_type_id == tax_pay_type:
            target_move = self.env['account.move'].browse(self.res_id)
            return target_move._action_tax_to_pay_wizard()

        # Periodic tax report reminder → open the tax report
        target_journal = self.env['account.journal'].browse(self.res_id)
        report_opts = {}
        if self.account_tax_closing_params:
            params = self.account_tax_closing_params
            fpos = (
                self.env['account.fiscal.position'].browse(params['fpos_id'])
                if params['fpos_id']
                else False
            )
            report_opts = self.env['account.move']._get_tax_closing_report_options(
                target_journal.company_id,
                fpos,
                self.env['account.report'].browse(params['report_id']),
                fields.Date.from_string(params['tax_closing_end_date']),
            )

        tax_report_action = self.env["ir.actions.actions"]._for_xml_id(
            "fusion_accounting.action_account_report_gt"
        )
        tax_report_action.update({
            'params': {'options': report_opts, 'ignore_session': True},
        })
        return tax_report_action
