<?php

namespace Modules\Bms\Http\Controllers\Api;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsPushSubscription;
use Modules\Bms\Services\Contracts\PushServiceContract;

/**
 * Web-push subscription management for both PWAs. The guard is inferred from
 * the authenticated principal (App\User = employee, App\Contact = client).
 */
class PushController extends ApiController
{
    /** Public VAPID key the PWA service worker subscribes with. */
    public function key(PushServiceContract $push)
    {
        return $this->ok(['enabled' => $push->enabled(), 'public_key' => $push->publicKey()]);
    }

    public function subscribe(Request $request)
    {
        $owner = $request->attributes->get('bms_owner');
        $businessId = $this->authBusinessId($request);
        $guard = $owner instanceof \App\User ? 'employee' : 'client';

        $data = $request->validate([
            'subscription'          => 'required|array',
            'subscription.endpoint' => 'required|string',
        ]);

        BmsPushSubscription::store($businessId, $guard, (int) $owner->id, $data['subscription'], substr((string) $request->userAgent(), 0, 255));

        return $this->ok(['subscribed' => true]);
    }

    public function unsubscribe(Request $request)
    {
        $data = $request->validate(['endpoint' => 'required|string']);
        BmsPushSubscription::where('endpoint_hash', hash('sha256', $data['endpoint']))->delete();

        return $this->ok(['unsubscribed' => true]);
    }
}
