# Fusion Accounting - Chart Template Extensions
# Populates deferred journal/account defaults when the module is installed

from odoo.addons.account.models.chart_template import template
from odoo import models


class FusionChartTemplate(models.AbstractModel):
    """Extends the chart-of-accounts template loader to supply default
    values for deferred-revenue and deferred-expense journals and
    accounts when Fusion Accounting is installed."""

    _inherit = 'account.chart.template'

    def _get_fusion_accounting_res_company(self, chart_template):
        """Return company-level defaults for deferred journals and
        accounts, falling back to the chart template data when the
        company does not yet have values configured."""
        current_company = self.env.company
        template_data = self._get_chart_template_data(chart_template)
        co_defaults = template_data['res.company'].get(current_company.id, {})

        # Ensure prerequisite XML-IDs exist for journals & accounts
        prerequisite_models = {
            key: val
            for key, val in template_data.items()
            if key in ['account.journal', 'account.account']
        }
        self._pre_reload_data(
            current_company,
            template_data['template_data'],
            prerequisite_models,
        )

        return {
            current_company.id: {
                'deferred_expense_journal_id': (
                    current_company.deferred_expense_journal_id.id
                    or co_defaults.get('deferred_expense_journal_id')
                ),
                'deferred_revenue_journal_id': (
                    current_company.deferred_revenue_journal_id.id
                    or co_defaults.get('deferred_revenue_journal_id')
                ),
                'deferred_expense_account_id': (
                    current_company.deferred_expense_account_id.id
                    or co_defaults.get('deferred_expense_account_id')
                ),
                'deferred_revenue_account_id': (
                    current_company.deferred_revenue_account_id.id
                    or co_defaults.get('deferred_revenue_account_id')
                ),
            },
        }

    def _get_chart_template_data(self, chart_template):
        """Augment the chart template data by assigning sensible
        defaults for deferred journals and accounts when none are
        explicitly defined in the template."""
        data = super()._get_chart_template_data(chart_template)

        for _co_id, co_vals in data['res.company'].items():
            # Default deferred expense journal → first general journal
            co_vals['deferred_expense_journal_id'] = (
                co_vals.get('deferred_expense_journal_id')
                or next(
                    (xid for xid, jdata in data['account.journal'].items()
                     if jdata['type'] == 'general'),
                    None,
                )
            )
            # Default deferred revenue journal → first general journal
            co_vals['deferred_revenue_journal_id'] = (
                co_vals.get('deferred_revenue_journal_id')
                or next(
                    (xid for xid, jdata in data['account.journal'].items()
                     if jdata['type'] == 'general'),
                    None,
                )
            )
            # Default deferred expense account → first current asset
            co_vals['deferred_expense_account_id'] = (
                co_vals.get('deferred_expense_account_id')
                or next(
                    (xid for xid, adata in data['account.account'].items()
                     if adata['account_type'] == 'asset_current'),
                    None,
                )
            )
            # Default deferred revenue account → first current liability
            co_vals['deferred_revenue_account_id'] = (
                co_vals.get('deferred_revenue_account_id')
                or next(
                    (xid for xid, adata in data['account.account'].items()
                     if adata['account_type'] == 'liability_current'),
                    None,
                )
            )

        return data
