# -*- coding: utf-8 -*-
# Copyright 2024-2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)
# Part of the Fusion Claim Assistant product family.

import logging

from . import models
from . import wizard

_logger = logging.getLogger(__name__)


def _load_adp_device_codes(env):
    """Post-init hook: load device codes then link products to them.

    Called on module install AND upgrade.  Each step is idempotent.
    """
    env['fusion.adp.device.code']._load_packaged_device_codes()
    _link_products_to_device_codes(env)


def _link_products_to_device_codes(env):
    """Populate x_fc_adp_device_code_id and x_fc_is_adp_product for
    existing products that already have a device code string set.

    Uses raw SQL for speed since this may touch hundreds of rows.
    """
    cr = env.cr

    cr.execute("""
        UPDATE product_template pt
        SET x_fc_adp_device_code_id = adc.id,
            x_fc_adp_price          = adc.adp_price,
            x_fc_is_adp_product     = TRUE
        FROM fusion_adp_device_code adc
        WHERE pt.x_fc_adp_device_code IS NOT NULL
          AND pt.x_fc_adp_device_code != ''
          AND adc.device_code = pt.x_fc_adp_device_code
          AND adc.active = TRUE
          AND pt.x_fc_adp_device_code_id IS NULL
    """)
    linked = cr.rowcount
    _logger.info("ADP migration: linked %d products to device code records", linked)

    cr.execute("""
        UPDATE product_template
        SET x_fc_is_adp_product = TRUE
        WHERE x_fc_adp_device_code IS NOT NULL
          AND x_fc_adp_device_code != ''
          AND (x_fc_is_adp_product IS NULL OR x_fc_is_adp_product = FALSE)
    """)
    toggled = cr.rowcount
    _logger.info("ADP migration: toggled x_fc_is_adp_product on %d products", toggled)
