<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserNotification;
use App\Services\AdminActivityLogger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NotificationController extends Controller
{
    public function index(): View
    {
        return view('admin.notifications', [
            'recent' => UserNotification::query()->latest('id')->limit(20)->get(),
        ]);
    }

    public function store(Request $request, AdminActivityLogger $logger): RedirectResponse
    {
        $validated = $request->validate([
            'title' => ['required', 'string', 'max:191'],
            'message' => ['required', 'string', 'max:1000'],
            'link' => ['nullable', 'string', 'max:191'],
            'role' => ['nullable', 'string', 'max:50'],
        ]);

        $role = $validated['role'] ?? 'user';

        DB::transaction(function () use ($validated, $role): void {
            User::query()
                ->where('role', $role)
                ->orderBy('id')
                ->chunkById(200, function ($users) use ($validated): void {
                    $now = now();
                    $rows = [];
                    foreach ($users as $user) {
                        $rows[] = [
                            'user_id' => $user->id,
                            'type' => 'broadcast',
                            'title' => $validated['title'],
                            'message' => $validated['message'],
                            'link' => $validated['link'] ?? null,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];
                    }
                    if ($rows !== []) {
                        UserNotification::query()->insert($rows);
                    }
                });
        });

        $logger->log('notification.broadcast', UserNotification::class, null, ['role' => $role]);

        return back()->with('status', 'Broadcast queued to users.');
    }
}
