<?php

namespace App\Services;

use App\Models\FcmToken;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class PushNotificationService
{
    /**
     * Envoyer une notification push à un utilisateur (tous ses appareils enregistrés).
     */
    public function sendToUser(User $user, string $title, string $body, array $data = []): void
    {
        $tokens = FcmToken::where('user_id', $user->id)->pluck('token');

        foreach ($tokens as $token) {
            $this->sendToToken($token, $title, $body, $data);
        }
    }

    /**
     * Envoyer à un token (Expo ou FCM).
     */
    public function sendToToken(string $token, string $title, string $body, array $data = []): bool
    {
        if (str_starts_with($token, 'ExponentPushToken[') || str_starts_with($token, 'ExpoPushToken[')) {
            return $this->sendExpoPush($token, $title, $body, $data);
        }

        return $this->sendFcmLegacy($token, $title, $body, $data);
    }

    private function sendExpoPush(string $expoToken, string $title, string $body, array $data): bool
    {
        $response = Http::acceptJson()->post('https://exp.host/--/api/v2/push/send', [
            'to' => $expoToken,
            'title' => $title,
            'body' => $body,
            'data' => $data,
            'sound' => 'default',
            'channelId' => 'default',
        ]);

        if (!$response->successful()) {
            Log::warning('Expo push failed', [
                'token' => substr($expoToken, 0, 30) . '...',
                'status' => $response->status(),
                'body' => $response->body(),
            ]);
            return false;
        }

        return true;
    }

    private function sendFcmLegacy(string $fcmToken, string $title, string $body, array $data): bool
    {
        $serverKey = config('services.fcm.server_key');
        if (empty($serverKey)) {
            Log::debug('FCM server key not set, skip push');
            return false;
        }

        $response = Http::withHeaders([
            'Authorization' => 'key=' . $serverKey,
            'Content-Type' => 'application/json',
        ])->post('https://fcm.googleapis.com/fcm/send', [
            'to' => $fcmToken,
            'notification' => [
                'title' => $title,
                'body' => $body,
                'sound' => 'default',
            ],
            'data' => $data,
        ]);

        if (!$response->successful()) {
            Log::warning('FCM push failed', [
                'status' => $response->status(),
                'body' => $response->body(),
            ]);
            return false;
        }

        return true;
    }
}
