<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class NotificationController extends Controller
{
    /**
     * Get notifications for the authenticated user (API endpoint)
     */
    public function index()
    {
        $user = Auth::user();
        
        $notifications = NotificationService::getUserNotifications($user, 50);
        $unreadCount = NotificationService::getUnreadCount($user);

        return response()->json([
            'notifications' => $notifications,
            'unread_count' => $unreadCount
        ]);
    }

    /**
     * Mark a specific notification as read
     */
    public function markAsRead($id)
    {

        $notification = Notification::where('id', $id)
            ->firstOrFail();

        $notification->markAsRead();

        return response()->json(['success' => true]);
    }

    /**
     * Mark all notifications as read for the authenticated user
     */
    public function markAllAsRead()
    {
        NotificationService::markAllAsRead(Auth::id());

        return response()->json(['success' => true]);
    }

    /**
     * Show all notifications page
     */
    public function all()
    {
        $userId = Auth::id();
        
        $notifications = Notification::where('user_id', $userId)
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return Inertia::render('Notifications/All', [
            'notifications' => $notifications
        ]);
    }

    /**
     * Delete a notification
     */
    public function destroy($id)
    {
        $notification = Notification::where('id', $id)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        $notification->delete();

        return response()->json(['success' => true]);
    }

    /**
     * Get unread count for the authenticated user
     */
    public function getUnreadCount()
    {
        $count = NotificationService::getUnreadCount(Auth::id());
        
        return response()->json(['count' => $count]);
    }
}
