<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Google\Client as GoogleClient;
use Illuminate\Support\Facades\Storage;

class SyncGoogleReviews extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'google:sync-reviews';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Synchronise les avis Google Business Profile';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('🔄 Début de la synchronisation des avis Google...');

        $client = new GoogleClient();
        $client->setClientId(config('services.google.client_id'));
        $client->setClientSecret(config('services.google.client_secret'));
        $client->setRedirectUri(route('google.callback'));
        $client->addScope('https://www.googleapis.com/auth/business.manage');
        $client->setAccessType('offline');

        $client->setAccessToken([
            'access_token' => config('services.google.access_token'),
            'refresh_token' => config('services.google.refresh_token'),
        ]);

        if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        }

        $accessToken = $client->getAccessToken()['access_token'];
        $accountID = config('services.google.business_account_id');
        $locationID = config('services.google.business_location_id');

        $this->info("🔐 Compte : $accountID / Location : " . $locationID);

        // 📝 Récupère les avis
        $reviewsResponse = Http::withToken($accessToken)
            ->get("https://mybusiness.googleapis.com/v4/accounts/{$accountID}/locations/{$locationID}/reviews");

        $reviews = $reviewsResponse->json()['reviews'] ?? [];

        if (count($reviews) === 0) {
            $this->warn("❌ Aucun avis");
        } else {
            $path = "google/reviews/" . str_replace(['accounts/', 'locations/', '/'], ['a_', 'l_', '_'], $locationID) . ".json";

// Charger les anciens avis s'ils existent
            $oldReviews = [];
            if (Storage::disk('local')->exists($path)) {
                $oldReviews = json_decode(Storage::disk('local')->get($path), true) ?? [];
            }

// Indexer les anciens avis par reviewId pour comparaison
            $oldReviewIds = array_column($oldReviews, null, 'reviewId');

// Fusion : ajouter uniquement les nouveaux avis
            foreach ($reviews as $newReview) {
                $oldReviewIds[$newReview['reviewId']] = $newReview;
            }

// Réindexer en tableau simple
            $mergedReviews = array_values($oldReviewIds);

// Écrire le nouveau cache
            Storage::disk('local')->put($path, json_encode($mergedReviews, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            $this->info("✅ " . count($mergedReviews) . " avis stockés (anciens + nouveaux) dans $path");
        }

        $this->info('✔️ Fin de synchronisation des avis Google.');
    }

    public static function getCachedReviews(string $locationID = null): array
    {
        if(!$locationID) {
            $locationID = config('services.google.business_location_id');
        }

        $path = "google/reviews/" . str_replace(['accounts/', 'locations/', '/'], ['a_', 'l_', '_'], $locationID) . ".json";

        if (!Storage::disk('local')->exists($path)) {
            throw new \Exception("Couldn't find $path");
        }

        return json_decode(Storage::disk('local')->get($path), true) ?? [];
    }
}
