# Fusion Accounting - Partner Extensions
# Partner ledger navigation, enriched display names, PDF report generation

from odoo import api, fields, models, _


class FusionResPartner(models.Model):
    """Extends partners with accounting-specific actions, enriched
    display-name computation, and PDF report attachment generation."""

    _name = 'res.partner'
    _inherit = 'res.partner'

    account_represented_company_ids = fields.One2many(
        comodel_name='res.company',
        inverse_name='account_representative_id',
    )

    # ---- Follow-Up ----
    def _get_followup_responsible(self):
        """Return the user responsible for follow-up on this partner."""
        return self.env.user

    # ---- Actions ----
    def open_partner_ledger(self):
        """Navigate to the partner ledger report filtered to this partner."""
        ledger_action = self.env["ir.actions.actions"]._for_xml_id(
            "fusion_accounting.action_account_report_partner_ledger"
        )
        ledger_action['params'] = {
            'options': {
                'partner_ids': self.ids,
                'unfold_all': len(self.ids) == 1,
            },
            'ignore_session': True,
        }
        return ledger_action

    def open_partner(self):
        """Open the partner form view for this record."""
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'res.partner',
            'res_id': self.id,
            'views': [[False, 'form']],
            'view_mode': 'form',
            'target': 'current',
        }

    # ---- Display Name ----
    @api.depends_context('show_more_partner_info')
    def _compute_display_name(self):
        """When the context flag ``show_more_partner_info`` is set,
        append the VAT number and country code to the partner name."""
        if not self.env.context.get('show_more_partner_info'):
            return super()._compute_display_name()
        for partner in self:
            extra_info = ""
            if partner.vat:
                extra_info += f" {partner.vat},"
            if partner.country_id:
                extra_info += f" {partner.country_id.code},"
            partner.display_name = f"{partner.name} - " + extra_info

    # ---- PDF Report Attachment ----
    def _get_partner_account_report_attachment(self, report, options=None):
        """Render the given accounting report as PDF for this partner
        and create an ``ir.attachment`` linked to the partner record.

        :param report:  An ``account.report`` record.
        :param options: Optional pre-computed report options.
        :returns:       The created ``ir.attachment`` record.
        """
        self.ensure_one()
        localised_report = report.with_context(lang=self.lang) if self.lang else report

        if not options:
            options = localised_report.get_options({
                'partner_ids': self.ids,
                'unfold_all': True,
                'unreconciled': True,
                'hide_account': True,
                'all_entries': False,
            })

        pdf_data = localised_report.export_to_pdf(options)
        return self.env['ir.attachment'].create([{
            'name': f"{self.name} - {pdf_data['file_name']}",
            'res_model': self._name,
            'res_id': self.id,
            'type': 'binary',
            'raw': pdf_data['file_content'],
            'mimetype': 'application/pdf',
        }])
