# This weekly digest function will run at 12:00pm on Friday in the Paris timezone
@inngest_client.create_function(
    fn_id="prepare-weekly-digest",
    trigger=inngest.TriggerCron(cron="TZ=Europe/Paris 0 12 * * 5")
)
async def prepare_weekly_digest(ctx: inngest.Context) -> None:
    # Load all the users from your database:
    users = await ctx.step.run(
        "load-users",
        lambda: db.load("SELECT * FROM users")
    )

    # 💡 Since we want to send a weekly digest to each one of these users
    # it may take a long time to iterate through each user and send an email.

    # Instead, we'll use this scheduled function to send an event to Inngest
    # for each user then handle the actual sending of the email in a separate
    # function triggered by that event.

    # ✨ This is known as a "fan-out" pattern ✨

    # 1️⃣ First, we'll create an event object for every user return in the query:
    events = [
        {
            "name": "app/send.weekly.digest",
            "data": {
                "user_id": user.id,
                "email": user.email,
            }
        }
        for user in users
    ]

    # 2️⃣ Now, we'll send all events in a single batch:
    await ctx.step.send_event("send-digest-events", events)

    # This function can now quickly finish and the rest of the logic will
    # be handled in the function below ⬇️