"""Fill pickup_day and pickup_date for existing group orders."""

from datetime import datetime
from datetime import timedelta


def migrate(cr, version):
    """
    Fill pickup_day and pickup_date for existing group orders.

    This ensures that existing group orders show delivery information.
    """
    from odoo import SUPERUSER_ID
    from odoo import api

    env = api.Environment(cr, SUPERUSER_ID, {})

    # Get all group orders that don't have pickup_day set
    group_orders = env["group.order"].search([("pickup_day", "=", False)])

    if not group_orders:
        return

    # Set default values: Friday (4) and one week from now
    today = datetime.now().date()

    # Find Friday of next week (day 4)
    days_until_friday = (4 - today.weekday()) % 7  # 4 = Friday
    if days_until_friday == 0:
        days_until_friday = 7
    friday = today + timedelta(days=days_until_friday)

    for order in group_orders:
        order.write(
            {
                "pickup_day": 4,  # Friday
                "pickup_date": friday,
                "delivery_notice": "Home delivery available.",
            }
        )
