<?php

namespace App\Services;

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

class PushService
{
    private const EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send';

    public static function send(
        User   $user,
        string $title,
        string $body,
        array  $data = []
    ): void {
        $tokens = Device::where('user_id', $user->id)
            ->where('active', true)
            ->whereNotNull('push_token')
            ->pluck('push_token');

        Log::info('PushService: tokens', [
            'user_id' => $user->id,
            'count'   => $tokens->count(),
            'tokens'  => $tokens->toArray(),
        ]);

        if ($tokens->isEmpty()) {
            return;
        }

        $messages = $tokens->map(fn ($token) => [
            'to'    => $token,
            'title' => $title,
            'body'  => $body,
            'data'  => $data,
            'sound' => 'default',
            'badge' => 1,
        ])->values()->toArray();

        try {
            $response = Http::withHeaders([
                'Accept'       => 'application/json',
                'Content-Type' => 'application/json',
            ])->post(self::EXPO_PUSH_URL, $messages);

            $receipts = $response->json();

            Log::info('PushService: response', [
                'status'   => $response->status(),
                'body'     => $receipts,
            ]);

            Log::info('Push sent', [
                'user_id'  => $user->id,
                'tokens'   => $tokens->count(),
                'response' => $receipts,
            ]);

            // Ungültige Tokens sofort deaktivieren
            if (is_array($receipts)) {
                self::handleReceipts($receipts, $tokens->toArray());
            }
        } catch (\Exception $e) {
            Log::error('Push failed', [
                'user_id' => $user->id,
                'error'   => $e->getMessage(),
            ]);
        }
    }

    public static function handleReceipts(array $receipts, array $tokens): void
    {
        foreach ($receipts as $i => $receipt) {
            if (($receipt['status'] ?? '') === 'error') {
                $details = $receipt['details'] ?? [];
                if (($details['error'] ?? '') === 'DeviceNotRegistered') {
                    Device::where('push_token', $tokens[$i] ?? '')
                        ->update(['active' => false]);
                }
            }
        }
    }
}
