<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    public function feed(Request $request): JsonResponse
    {
        $limit = min(max((int) $request->query('limit', 15), 1), 50);
        $user = Auth::user();
        if (! $user instanceof User) {
            return response()->json(['count' => 0, 'items' => []], 401);
        }

        $items = $user->notifications()
            ->when($request->boolean('unread_only'), fn ($q) => $q->whereNull('read_at'))
            ->latest()
            ->limit($limit)
            ->get()
            ->map(fn ($notification) => $this->formatNotification($notification))
            ->values()
            ->all();

        return response()->json([
            'count' => $user->unreadNotifications()->count(),
            'items' => $items,
        ]);
    }

    public function markRead(Request $request, string $id): JsonResponse
    {
        $user = Auth::user();
        if (! $user instanceof User) {
            return response()->json(['message' => 'Unauthenticated.'], 401);
        }

        $notification = $user->notifications()->where('id', $id)->first();
        if (! $notification) {
            return response()->json(['message' => 'Notification not found.'], 404);
        }

        $notification->markAsRead();

        return response()->json(['ok' => true, 'item' => $this->formatNotification($notification->fresh())]);
    }

    public function destroy(string $id): JsonResponse
    {
        $user = Auth::user();
        if (! $user instanceof User) {
            return response()->json(['message' => 'Unauthenticated.'], 401);
        }

        $notification = $user->notifications()->where('id', $id)->first();
        if (! $notification) {
            return response()->json(['message' => 'Notification not found.'], 404);
        }

        $notification->delete();

        return response()->json([
            'ok' => true,
            'count' => $user->unreadNotifications()->count(),
        ]);
    }

    public function markAllRead(): JsonResponse
    {
        $user = Auth::user();
        if ($user instanceof User) {
            $user->unreadNotifications->markAsRead();
        }

        return response()->json(['ok' => true]);
    }

    protected function formatNotification($notification): array
    {
        $data = is_array($notification->data) ? $notification->data : [];

        return [
            'id' => $notification->id,
            'message' => (string) ($data['message'] ?? 'New notification'),
            'url' => $data['url'] ?? null,
            'type' => $data['type'] ?? null,
            'leave_id' => $data['leave_id'] ?? null,
            'month' => $data['month'] ?? null,
            'year' => $data['year'] ?? null,
            'read_at' => $notification->read_at?->toDateTimeString(),
            'created_at' => $notification->created_at?->toDateTimeString(),
        ];
    }
}
