<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\AdminAuditLogger;
use App\Services\InAppNotificationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminPushController extends Controller
{
    public function sendTest(
        Request $request,
        InAppNotificationService $notificationService,
        AdminAuditLogger $auditLogger,
    ): JsonResponse {
        $admin = $request->user();
        abort_unless($admin?->role === 'admin', 403);

        $data = $request->validate([
            'user_id' => ['required', 'integer', 'exists:users,id'],
            'type' => ['nullable', 'string', 'max:120'],
            'title' => ['required', 'string', 'max:255'],
            'body' => ['required', 'string', 'max:1000'],
            'payload' => ['nullable', 'array'],
        ]);

        $target = User::query()->findOrFail((int) $data['user_id']);

        $notification = $notificationService->notifyUser(
            userId: $target->id,
            type: $data['type'] ?? 'admin.push_test',
            title: $data['title'],
            body: $data['body'],
            payload: $data['payload'] ?? [],
        );

        $auditLogger->log($admin, 'push.test', $target, [
            'notification_id' => $notification->id,
            'type' => $notification->type,
            'title' => $notification->title,
        ]);

        return response()->json([
            'data' => $notification,
        ], 202);
    }
}
