<?php

namespace App\Http\Controllers;

use App\Jobs\SendWebPushToUser;
use App\Models\PushSubscription;
use App\Services\WebPushSender;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PushSubscriptionController extends Controller
{
    public function vapidPublicKey(): JsonResponse
    {
        $key = config('webpush.vapid.public_key');
        if (! filled($key)) {
            return response()->json(['message' => __('Push notifications are not configured on the server.')], 503);
        }

        return response()->json(['publicKey' => $key]);
    }

    public function subscribe(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'endpoint' => ['required', 'string', 'max:4096'],
            'keys.p256dh' => ['required', 'string', 'max:512'],
            'keys.auth' => ['required', 'string', 'max:255'],
            'contentEncoding' => ['nullable', 'string', 'in:aesgcm,aes128gcm'],
        ]);

        $encoding = $validated['contentEncoding'] ?? 'aes128gcm';

        PushSubscription::query()->updateOrCreate(
            ['endpoint' => $validated['endpoint']],
            [
                'user_id' => $request->user()->id,
                'public_key' => $validated['keys']['p256dh'],
                'auth_token' => $validated['keys']['auth'],
                'content_encoding' => $encoding,
            ],
        );

        return response()->json(['ok' => true]);
    }

    public function unsubscribe(Request $request): Response
    {
        $validated = $request->validate([
            'endpoint' => ['required', 'string', 'max:4096'],
        ]);

        PushSubscription::query()
            ->where('user_id', $request->user()->id)
            ->where('endpoint', $validated['endpoint'])
            ->delete();

        return response()->noContent();
    }

    public function test(Request $request): JsonResponse
    {
        if (! app(WebPushSender::class)->isConfigured()) {
            return response()->json(['message' => __('Push notifications are not configured on the server.')], 503);
        }

        SendWebPushToUser::dispatch(
            $request->user()->id,
            config('app.name', 'Collabs'),
            __('Collabs push is working.'),
            '/app',
            'collabs-test',
        );

        return response()->json(['queued' => true]);
    }
}
