<?php

namespace App\Http\Controllers;

use App\Models\PushSubscription;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PushSubscriptionController extends Controller
{
    public function vapidPublicKey(): JsonResponse
    {
        $publicKey = (string) config('webpush.vapid.public_key', '');

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

    public function subscribe(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'endpoint' => ['required', 'string', 'max:2048'],
            'keys.p256dh' => ['required', 'string'],
            'keys.auth' => ['required', 'string'],
            'contentEncoding' => ['nullable', 'string', 'max:32'],
            'deviceLabel' => ['nullable', 'string', 'max:120'],
        ]);

        $endpoint = trim((string) $validated['endpoint']);
        $p256dh = trim((string) data_get($validated, 'keys.p256dh'));
        $auth = trim((string) data_get($validated, 'keys.auth'));
        $encoding = strtolower(trim((string) ($validated['contentEncoding'] ?? 'aesgcm')));
        if (! in_array($encoding, ['aesgcm', 'aes128gcm'], true)) {
            $encoding = 'aesgcm';
        }

        PushSubscription::query()->updateOrCreate(
            ['endpoint_hash' => hash('sha256', $endpoint)],
            [
                'user_id' => (int) $request->user()->id,
                'endpoint' => $endpoint,
                'public_key' => $p256dh,
                'auth_token' => $auth,
                'content_encoding' => $encoding,
                'user_agent' => (string) $request->userAgent(),
                'device_label' => (string) ($validated['deviceLabel'] ?? ''),
            ]
        );

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

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

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

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