<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * HeaderNotificationController
 *
 * Handles AJAX notification fetching and mark-read actions for the app header.
 * All responses are scoped strictly to the authenticated user.
 *
 * Requirements: 3.3, 3.4, 3.5, 3.6, 10.6
 */
class HeaderNotificationController extends Controller
{
    /**
     * Icon mapping by notification type class name suffix.
     */
    private array $iconMap = [
        'ApprovalNotification' => 'fa-check-circle text-green-400',
        'ReminderNotification' => 'fa-clock text-amber-400',
        'AlertNotification'    => 'fa-exclamation-circle text-red-400',
    ];

    /**
     * GET /api/header/notifications
     *
     * Returns the authenticated user's latest 20 notifications with computed fields.
     *
     * Requirements: 3.3, 3.4
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();

        $notifications = $user->notifications()->latest()->limit(20)->get();

        $mapped = $notifications->map(function ($n) {
            $data = $n->data ?? [];

            return [
                'id'         => $n->id,
                'type'       => $n->type,
                'title'      => $data['title'] ?? 'Notification',
                'message'    => $data['message'] ?? '',
                'time_ago'   => $n->created_at->diffForHumans(),
                'is_read'    => $n->read_at !== null,
                'action_url' => $data['action_url'] ?? null,
                'icon'       => $this->resolveIcon($n->type),
            ];
        });

        $unreadCount = $mapped->where('is_read', false)->count();

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

    /**
     * POST /api/header/notifications/{id}/read
     *
     * Marks a single notification as read. Returns 404 if the notification
     * does not belong to the authenticated user.
     *
     * Requirements: 3.5, 10.6
     */
    public function markRead(Request $request, string $id): JsonResponse
    {
        $notification = $request->user()
            ->notifications()
            ->where('id', $id)
            ->first();

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

        $notification->markAsRead();

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

    /**
     * POST /api/header/notifications/read-all
     *
     * Marks all unread notifications for the authenticated user as read.
     *
     * Requirements: 3.6
     */
    public function markAllRead(Request $request): JsonResponse
    {
        $request->user()->unreadNotifications->markAsRead();

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

    /**
     * Resolve a FontAwesome icon class from the notification type class name.
     */
    private function resolveIcon(string $type): string
    {
        foreach ($this->iconMap as $suffix => $icon) {
            if (str_ends_with($type, $suffix)) {
                return $icon;
            }
        }

        return 'fa-bell text-blue-400';
    }
}
