# Fusion Accounting - Fiscal Position Extensions
# Automated draft tax closing moves for foreign VAT positions

from odoo import models


class FusionFiscalPosition(models.Model):
    """Extends fiscal positions to generate draft tax-closing entries
    whenever a foreign VAT number is set or updated."""

    _inherit = 'account.fiscal.position'

    def _inverse_foreign_vat(self):
        """When the foreign_vat field is written, propagate draft
        closing moves for each affected fiscal position."""
        super()._inverse_foreign_vat()
        for fpos in self:
            if fpos.foreign_vat:
                fpos._create_draft_closing_move_for_foreign_vat()

    def _create_draft_closing_move_for_foreign_vat(self):
        """For every existing draft tax-closing entry, ensure a
        corresponding closing move exists for this fiscal position."""
        self.ensure_one()
        draft_closings = self.env['account.move'].search([
            ('tax_closing_report_id', '!=', False),
            ('state', '=', 'draft'),
        ])
        for closing_date, grouped_entries in draft_closings.grouped('date').items():
            for entry in grouped_entries:
                self.company_id._get_and_update_tax_closing_moves(
                    closing_date,
                    entry.tax_closing_report_id,
                    fiscal_positions=self,
                )
