<?php
// cron/strava-refresh.php — Hebdo lundi 03h00
// Refresh tokens Strava expirant dans les 7 prochains jours

require_once __DIR__ . '/_bootstrap.php';
use App\Services\StravaService;
use Illuminate\Database\Capsule\Manager as DB;

$strava = new StravaService();

$expirantBientot = DB::table('users')
    ->where('strava_connected', 1)
    ->whereNotNull('strava_refresh_token')
    ->where('strava_token_expires', '<', time() + (7 * 86400))
    ->get();

$nb = 0;
foreach ($expirantBientot as $user) {
    try {
        $ok = $strava->refreshToken($user->id);
        if ($ok) $nb++;
    } catch (\Exception $e) {
        error_log('[CRON strava-refresh] Erreur user ' . $user->id . ': ' . $e->getMessage());
    }
}

error_log('[CRON strava-refresh] ' . date('c') . " — {$nb} tokens rafraîchis");
