<?php

namespace App\Http\Controllers\Admin\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AdminNotificationController extends Controller
{
    /**
     * Get latest 20 notifications for the authenticated admin.
     */
    public function index(Request $request): JsonResponse
    {
        $admin = $request->user();
        $cacheKey = "admin:{$admin->id}:notifications:latest";

        $notifications = Cache::remember($cacheKey, 300, function () use ($admin) {
            return $admin->notifications()
                ->latest()
                ->limit(20)
                ->get()
                ->map(fn ($n) => [
                    'id' => $n->id,
                    'type' => $n->data['notification_type'] ?? 'system',
                    'title' => $n->data['title'] ?? '',
                    'message' => $n->data['message'] ?? '',
                    'severity' => $n->data['severity'] ?? 'info',
                    'icon' => $n->data['icon'] ?? 'fas fa-bell',
                    'url' => $n->data['url'] ?? null,
                    'read' => $n->read_at !== null,
                    'created_at' => $n->created_at->toIso8601String(),
                ]);
        });

        return response()->json(['data' => $notifications]);
    }

    /**
     * Get unread notification count.
     */
    public function unreadCount(Request $request): JsonResponse
    {
        $admin = $request->user();
        $cacheKey = "admin:{$admin->id}:notifications:unread_count";

        $count = Cache::remember($cacheKey, 300, function () use ($admin) {
            return $admin->unreadNotifications()->count();
        });

        return response()->json(['count' => $count]);
    }

    /**
     * Mark a single notification as read.
     */
    public function markAsRead(Request $request, string $id): JsonResponse
    {
        $admin = $request->user();
        $notification = $admin->notifications()->where('id', $id)->first();

        if (! $notification) {
            return response()->json(['message' => 'Notification not found'], 404);
        }

        $notification->markAsRead();
        $this->invalidateCache($admin->id);

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

    /**
     * Mark all notifications as read.
     */
    public function markAllAsRead(Request $request): JsonResponse
    {
        $admin = $request->user();
        $admin->unreadNotifications->markAsRead();
        $this->invalidateCache($admin->id);

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

    private function invalidateCache(int $adminId): void
    {
        Cache::forget("admin:{$adminId}:notifications:unread_count");
        Cache::forget("admin:{$adminId}:notifications:latest");
    }
}
