<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\SendBroadcastChannelsJob;
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'],
            'channels' => ['nullable', 'array'],
            'channels.*' => ['string', 'in:email,whatsapp,sms'],
        ]);

        $role = $validated['role'] ?? 'user';
        $channels = array_values(array_unique($validated['channels'] ?? []));

        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);
                    }
                });
        });

        if ($channels !== []) {
            SendBroadcastChannelsJob::dispatch(
                $role,
                $validated['title'],
                $validated['message'],
                $validated['link'] ?? null,
                $channels
            );
        }

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

        return back()->with('status', $channels === []
            ? 'Broadcast saved to in-app notifications.'
            : 'Broadcast saved and external channel delivery queued.');
    }
}
