<?php

namespace App\Http\Controllers\Web\Bo;

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

class PushController extends Controller
{
    public function sendTest(
        Request $request,
        InAppNotificationService $notificationService,
        AdminAuditLogger $auditLogger,
    ): RedirectResponse {
        $admin = $request->user();

        $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'],
        ]);

        $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: [
                'source' => 'bo',
                'admin_id' => $admin?->id,
            ],
        );

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

        return back()->with(
            'status',
            sprintf('Push test envoye a %s (#%d).', $target->name, $target->id),
        );
    }
}
