"""Pre-migration for the partner_commission_management → kj_affiliate_widget
merge (v18.0.2.4.0).

* Rewrite ``ir_model_data.module`` rows so the legacy xmlids resolve under
  the merged module — keeps existing commission records intact.
* Drop the legacy module's ``ir_module_module`` state to ``'uninstalled'``
  so Odoo doesn't try to load files that no longer exist.
* Clear the ``noupdate`` stored flag for the two relocated mail templates
  so the new bodies re-import on ``-u``. (See kj_email_layout memory for
  the noupdate stored-flag trap.)
"""

import logging

_logger = logging.getLogger(__name__)


# (legacy xmlid base, new xmlid base) — module-relative ids that must
# follow the relocated record. View ids and action ids that don't appear
# here aren't referenced from outside the legacy module's own data files
# (which are being dropped), so they don't need a rename.
_RELOCATIONS = [
    "product_commission_data",
    "ir_cron_monthly_commission_calculation",
    "email_template_affiliate_monthly_summary",
    "email_template_affiliate_transaction_admin",
    "report_partner_commission",
    "report_partner_commission_template",
    "report_partner_commission_action",
    "action_job_partner_commission",
    # Model + access xmlids: ir.model rows are global, but ir.model.data
    # references the source module — rewrite them too so they're not
    # garbage-collected when partner_commission_management is uninstalled.
    "model_job_partner_commission",
    "model_hr_job",
    "access_job_partner_commission_portal_user",
    "access_job_partner_commission_r_user",
    "access_job_partner_commission_crud_user",
]


def migrate(cr, version):
    cr.execute("""
        SELECT id, state FROM ir_module_module
        WHERE name = 'partner_commission_management'
    """)
    row = cr.fetchone()
    if not row:
        _logger.info(
            "partner_commission_management not present; skipping merge pre-migration",
        )
        return
    module_id, state = row
    _logger.info(
        "Merging partner_commission_management (state=%s) into kj_affiliate_widget",
        state,
    )

    # 1) Rewrite the relevant ir_model_data rows so the new module owns
    #    them. We pin to the exact names to avoid stealing anything we
    #    didn't intend (e.g. menus that no longer exist in the new layout).
    for name in _RELOCATIONS:
        cr.execute(
            """
            UPDATE ir_model_data
               SET module = 'kj_affiliate_widget',
                   noupdate = FALSE
             WHERE module = 'partner_commission_management'
               AND name = %s
            """,
            (name,),
        )
        if cr.rowcount:
            _logger.info("  rewrote %s.%s → kj_affiliate_widget.%s",
                         "partner_commission_management", name, name)

    # 2) Drop legacy ir.ui.view records on job.partner.commission that
    #    have no surviving xmlid. Without this, the old list view (with
    #    only 4 columns) shadows the new 9-column one because Odoo's
    #    view resolution by model+type picks the lowest-priority match
    #    and they share priority=16. We must do this BEFORE clearing
    #    ir_model_data, because we identify orphans by the upcoming
    #    DELETE of legacy module rows.
    cr.execute(
        """
        DELETE FROM ir_ui_view
         WHERE model = 'job.partner.commission'
           AND id IN (
               SELECT res_id FROM ir_model_data
                WHERE module = 'partner_commission_management'
                  AND model = 'ir.ui.view'
           )
        """
    )
    _logger.info("  dropped %d legacy ir_ui_view rows for job.partner.commission",
                 cr.rowcount)

    # Same for legacy menus owned by the old module.
    cr.execute(
        """
        DELETE FROM ir_ui_menu
         WHERE id IN (
               SELECT res_id FROM ir_model_data
                WHERE module = 'partner_commission_management'
                  AND model = 'ir.ui.menu'
           )
        """
    )
    _logger.info("  dropped %d legacy ir_ui_menu rows", cr.rowcount)

    # 3) Mark anything else owned by the legacy module as orphaned. Odoo
    #    cleans them up on next module list refresh.
    cr.execute(
        """
        DELETE FROM ir_model_data
         WHERE module = 'partner_commission_management'
        """
    )
    _logger.info("  cleared %d remaining legacy ir_model_data rows", cr.rowcount)

    # 3) Flip the legacy module to uninstalled so the registry skips it
    #    on this upgrade. Files no longer exist on disk — leaving it
    #    installed would crash module loading.
    cr.execute(
        """
        UPDATE ir_module_module
           SET state = 'uninstalled', latest_version = NULL
         WHERE id = %s
        """,
        (module_id,),
    )
