import logging

from odoo import http
from odoo.http import request

from odoo.addons.kj_search_elasticsearch.controllers.dynamic_search_api import DynamicSearchAPI

from .widget_api import get_affiliate_job_domain

_logger = logging.getLogger(__name__)


class AffiliateSearchFilter(DynamicSearchAPI):
    """Extend the ES search API to apply affiliate job filters.

    When the OWL JobFacetedFilters component passes affiliate_ref,
    the ES results are post-filtered by the affiliate's job domain.
    """

    @http.route()
    def search(self, model, **params):
        """Override to inject affiliate job filtering as a pre-filter.

        Pre-fetches allowed job IDs from the affiliate's filter config
        and injects them as a favorite_job_ids filter. ES then only
        returns jobs within the allowed set.
        """
        affiliate_ref = params.get('affiliate_ref', '')
        if affiliate_ref and model == 'hr.job':
            try:
                aff_config = (
                    request.env['affiliate.widget.config']
                    .sudo()
                    .search(
                        [('widget_key', '=', affiliate_ref), ('is_active', '=', True)],
                        limit=1,
                    )
                )
                if aff_config:
                    aff_domain = get_affiliate_job_domain(aff_config)
                    if aff_domain:
                        import json
                        # Pre-fetch allowed job IDs
                        Job = request.env['hr.job'].sudo()
                        allowed = Job.search(
                            [('is_published', '=', True), ('active', '=', True)] + aff_domain,
                            limit=5000,
                        )
                        if allowed:
                            # Inject as favorite_job_ids — ES already supports ID filtering
                            params['favorite_job_ids'] = json.dumps(allowed.ids)
                            _logger.info(
                                "Affiliate pre-filter [%s]: %d allowed job IDs",
                                affiliate_ref, len(allowed),
                            )
            except Exception as e:
                _logger.warning("Affiliate pre-filter error: %s", e)

        return super().search(model, **params)
