<?php

namespace App\Http\Controllers\Api\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\Tenant\AdminPushSubscriptionDeleteRequest;
use App\Http\Requests\Tenant\AdminPushSubscriptionStoreRequest;
use App\Services\TenantAdminPushSubscriptionService;
use Illuminate\Http\JsonResponse;

class AdminPushSubscriptionController extends Controller
{
    public function store(
        AdminPushSubscriptionStoreRequest $request,
        TenantAdminPushSubscriptionService $subscriptions
    ): JsonResponse {
        $tenant = $request->attributes->get('tenant') ?? $request->user()?->tenant;

        if (! $tenant) {
            return response()->json([
                'error' => [
                    'code' => 'tenant_context_missing',
                    'title' => 'Tenant context missing',
                    'message' => 'Unable to resolve tenant for push subscriptions.',
                ],
            ], 403);
        }

        $payload = array_merge($request->validated(), [
            'language' => $request->getPreferredLanguage() ?? $request->headers->get('Accept-Language'),
            'user_agent' => (string) $request->userAgent(),
        ]);

        $subscription = $subscriptions->register($tenant, $request->user(), $payload);

        return response()->json([
            'id' => $subscription->id,
            'status' => $subscription->status,
        ], 201);
    }

    public function destroy(
        AdminPushSubscriptionDeleteRequest $request,
        TenantAdminPushSubscriptionService $subscriptions
    ): JsonResponse {
        $tenant = $request->attributes->get('tenant') ?? $request->user()?->tenant;

        if (! $tenant) {
            return response()->json([
                'error' => [
                    'code' => 'tenant_context_missing',
                    'title' => 'Tenant context missing',
                    'message' => 'Unable to resolve tenant for push subscriptions.',
                ],
            ], 403);
        }

        $validated = $request->validated();
        $revoked = $subscriptions->revoke($tenant, $validated['endpoint'], $request->user());

        return response()->json([
            'status' => $revoked ? 'revoked' : 'not_found',
        ]);
    }
}
