# Copyright 2026 Criptomart
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo import api, models
from odoo.osv import expression


class MembershipLine(models.Model):
    _inherit = "membership.membership_line"

    def _search(self, domain, offset=0, limit=None, order=None):
        if self.env.context.get("include_associate_members"):
            domain = self._expand_domain_for_associates(domain)
        return super()._search(domain, offset=offset, limit=limit, order=order)

    def _expand_domain_for_associates(self, domain):
        country_id = None
        post_name = None
        for leaf in domain:
            if isinstance(leaf, (list, tuple)) and len(leaf) == 3:
                field, operator, value = leaf
                if field == "partner.country_id" and operator == "=":
                    country_id = value
                elif (
                    field in ("partner.name", "partner.website_description")
                    and operator == "ilike"
                ):
                    post_name = value
        if country_id is None and not post_name:
            return domain
        associate_domain = [
            ("associate_member", "!=", False),
            ("website_published", "=", True),
        ]
        if country_id is not None:
            associate_domain.append(("country_id", "=", country_id))
        if post_name:
            associate_domain += [
                "|",
                ("name", "ilike", post_name),
                ("website_description", "ilike", post_name),
            ]
        host_ids = (
            self.env["res.partner"]
            .sudo()
            .search(associate_domain)
            .associate_member.ids
        )
        if not host_ids:
            return domain
        return expression.OR([domain, [("partner", "in", host_ids)]])

    @api.model
    def _get_associate_partners(
        self, host_partner_ids, country_id=None, post_name=None
    ):
        if not host_partner_ids:
            return self.env["res.partner"]
        domain = [
            ("associate_member", "in", tuple(host_partner_ids)),
            ("website_published", "=", True),
        ]
        if country_id:
            domain.append(("country_id", "=", country_id))
        if post_name:
            domain += [
                "|",
                ("name", "ilike", post_name),
                ("website_description", "ilike", post_name),
            ]
        return self.env["res.partner"].sudo().search(domain)

    def _get_published_companies(self, limit=None):
        if not self.ids:
            return []
        limit_clause = "" if limit is None else " LIMIT %d" % limit
        self.env.cr.execute(
            """
            SELECT DISTINCT p.id
            FROM res_partner p
            INNER JOIN membership_membership_line m
              ON (p.id = m.partner OR p.associate_member = m.partner)
            WHERE p.is_published
              AND p.is_company
              AND m.id IN %s
            ORDER BY p.id
            """
            + limit_clause,
            (tuple(self.ids),),
        )
        return [row[0] for row in self.env.cr.fetchall()]
