<?php
set_time_limit(60);

return [
  'pattern' => '/refresh-cache.json',
  'method' => 'POST',
  'action' => function() {
    $json = file_get_contents('php://input');
    $data = json_decode($json);

    if ($data->pageUri === 'projects') {
      $projects = page('projects')->children();

      // Support du batch processing
      $offset = isset($data->offset) ? intval($data->offset) : 0;
      $limit = isset($data->limit) ? intval($data->limit) : 10; // 10 projets par batch par défaut
      $total = $projects->count();

      // Slice pour ne traiter qu'un batch
      $batch = $projects->slice($offset, $limit);
      $processed = 0;

      foreach ($batch as $project) {
        try {
          $project->rebuildStepsCache();
          $project->invalidateNotificationsCache();

          $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT, 'Europe/Paris');
          $project->update([
            'lastCacheUpdate' => $formatter->format(time())
          ]);
          $processed++;
        } catch (\Throwable $e) {
          error_log("Error refreshing cache for project {$project->slug()}: " . $e->getMessage());
        }
      }

      $remaining = max(0, $total - ($offset + $processed));
      $hasMore = $remaining > 0;

      return [
        'status' => 'success',
        'message' => "Batch terminé : $processed projets traités.",
        'processed' => $offset + $processed,
        'total' => $total,
        'remaining' => $remaining,
        'hasMore' => $hasMore,
        'nextOffset' => $hasMore ? $offset + $limit : null
      ];
    } else {
      try {
        $page = page($data->pageUri);
      } catch (\Throwable $th) {
        return [
          'status' => 'error',
          'message' => 'Impossible de rafraîchir le cache de la page : ' . $data->pageUri . '.',
          'details' => $th->getMessage(),
          'file' => $th->getFile(),
          'line' > $th->getLine()
        ];
      }

      $project = $page->template() == 'project' ? 
        $page 
        : $page->parents()->findBy('template', 'project');

      if (!$project) {
        return [
          'status' => 'error',
          'message' => 'Impossible de rafraîchir les données de la page ' . $data->pageUri . '. Aucun projet correspondant.'
        ];
      }

      $project->rebuildStepsCache();
      
      $formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT, 'Europe/Paris');
      $project->update([
        'lastCacheUpdate' => $formatter->format(time())
      ]);

      
      return [
        'status' => 'success',
        'message' => 'Données de la page ' . $data->pageUri . ' rafraîchie avec succès.'
      ];
    }
  }
];