<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\API\BaseApiController;
use App\Models\User;
use App\Notifications\ManualNotification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminNotificationController extends BaseApiController
{
    /** List all notifications sent to investors */
    public function index(): JsonResponse
    {
        $notifications = DB::table('notifications')
            ->where('notifiable_type', User::class)
            ->whereJsonContains('data->type', 'info')
            ->orWhere(function ($q) {
                $q->where('notifiable_type', User::class)
                  ->whereNotNull('data');
            })
            ->join('users', 'users.id', '=', 'notifications.notifiable_id')
            ->select(
                'notifications.id',
                'notifications.data',
                'notifications.read_at',
                'notifications.created_at',
                'users.name as user_name',
                'users.email as user_email',
            )
            ->orderByDesc('notifications.created_at')
            ->paginate(30);

        return $this->paginatedResponse($notifications);
    }

    /** Send notification to one investor or all investors */
    public function send(Request $request): JsonResponse
    {
        $data = $request->validate([
            'title'      => 'required|string|max:255',
            'message'    => 'required|string',
            'type'       => 'in:info,success,warning,error',
            'action_url' => 'nullable|url',
            'target'     => 'required|in:all,user',
            'user_id'    => 'required_if:target,user|exists:users,id',
        ]);

        $notification = new ManualNotification(
            $data['title'],
            $data['message'],
            $data['type'] ?? 'info',
            $data['action_url'] ?? null,
        );

        if ($data['target'] === 'all') {
            $users = User::role('investor')->get();
            foreach ($users as $user) {
                $user->notify($notification);
            }
            $count = $users->count();
            $msg = "Notificação enviada a {$count} investidores";
        } else {
            $user = User::findOrFail($data['user_id']);
            $user->notify($notification);
            $msg = "Notificação enviada a {$user->name}";
        }

        activity('notifications')->causedBy($request->user())->log($msg);

        return $this->successResponse(null, $msg);
    }
}
