"""Backfill the URL slug of consumer group orders created before this version.

Public pages moved from /eskaera/<id> to /eskaera/<slug>. Orders that already
existed have no slug yet, so they would not be reachable until saved again.
Generate one from their name, keeping it unique.
"""

import logging

from odoo import SUPERUSER_ID
from odoo import api

_logger = logging.getLogger(__name__)


def migrate(cr, version):
    if not version:
        return

    # tracking_disable: `slug` is a tracked field, backfilling it would post a
    # chatter message and notify the followers of every pre-existing order.
    env = api.Environment(cr, SUPERUSER_ID, {"tracking_disable": True})
    orders = env["group.order"].search([("slug", "=", False)], order="id")
    for order in orders:
        # One write at a time: the search inside `_generate_unique_slug` flushes
        # the previous one, so two orders sharing a name get distinct slugs.
        order.slug = order._generate_unique_slug(order.name)

    if orders:
        _logger.info(
            "Generated URL slugs for %d consumer group orders: %s",
            len(orders),
            ", ".join(orders.mapped("slug")),
        )
