<?php

namespace Modules\VetStaffPortal\Http\Controllers\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetStaffPortal\Entities\VsPushSubscription;

class PushController extends Controller
{
    /** Public — the PWA fetches this before pushManager.subscribe(). */
    public function vapidKey(): JsonResponse
    {
        $key = config('portal_push.public_key');
        if (! $key) {
            return response()->json(['message' => 'Push notifications are not configured for this server.'], 503);
        }
        return response()->json(['public_key' => $key]);
    }

    public function subscribe(Request $request): JsonResponse
    {
        $data = $request->validate([
            'endpoint'     => 'required|url|max:500',
            'keys.p256dh'  => 'required|string|max:191',
            'keys.auth'    => 'required|string|max:64',
            'categories'   => 'nullable|array',
            'categories.*' => 'in:' . implode(',', VsPushSubscription::CATEGORIES),
        ]);

        $user = auth()->user();

        $sub = VsPushSubscription::updateOrCreate(
            ['user_id' => $user->id, 'endpoint' => $data['endpoint']],
            [
                'business_id'          => $user->business_id,
                'p256dh_key'           => $data['keys']['p256dh'],
                'auth_key'             => $data['keys']['auth'],
                'user_agent'           => $request->userAgent(),
                'categories'           => $data['categories'] ?? VsPushSubscription::CATEGORIES,
                'consecutive_failures' => 0,
            ]
        );

        return response()->json(['id' => $sub->id, 'categories' => $sub->categories]);
    }

    public function preferences(Request $request): JsonResponse
    {
        $data = $request->validate([
            'endpoint'     => 'required|url',
            'categories'   => 'required|array',
            'categories.*' => 'in:' . implode(',', VsPushSubscription::CATEGORIES),
        ]);

        $sub = VsPushSubscription::where('user_id', auth()->id())
            ->where('endpoint', $data['endpoint'])->first();
        if (! $sub) return response()->json(['message' => 'Subscription not found.'], 404);

        $sub->forceFill(['categories' => $data['categories']])->save();
        return response()->json(['categories' => $sub->categories]);
    }

    public function unsubscribe(Request $request): JsonResponse
    {
        $data = $request->validate(['endpoint' => 'required|url']);
        VsPushSubscription::where('user_id', auth()->id())
            ->where('endpoint', $data['endpoint'])->delete();
        return response()->json(['ok' => true]);
    }
}
