<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AdminNotification;
use Illuminate\Http\Request;

class NotificationsController extends Controller
{
    /**
     * Public feed of sent admin notifications for the app.
     * Supports ?limit= and ?page= for basic pagination.
     */
    public function index(Request $request)
    {
        $limit = (int) $request->input('limit', 20);
        $limit = max(5, min(50, $limit));

        $query = AdminNotification::query()
            ->where('status', 'sent')
            ->orderByDesc('created_at');

        // If page is provided, paginate, else simple take
        if ($request->filled('page')) {
            $paginator = $query->paginate($limit)->withQueryString();
            $items = $paginator->items();
            return response()->json([
                'status' => 'success',
                'data' => array_map(fn ($n) => [
                    'id' => $n->id,
                    'title' => $n->title,
                    'message' => $n->message,
                    'url' => $n->url,
                    'image_url' => $n->image_url,
                    'created_at' => $n->created_at?->toIso8601String(),
                    'type' => 'info',
                ], $items),
                'meta' => [
                    'current_page' => $paginator->currentPage(),
                    'last_page' => $paginator->lastPage(),
                    'per_page' => $paginator->perPage(),
                    'total' => $paginator->total(),
                ],
            ]);
        }

        $items = $query->limit($limit)->get()->map(function ($n) {
            return [
                'id' => $n->id,
                'title' => $n->title,
                'message' => $n->message,
                'url' => $n->url,
                'image_url' => $n->image_url,
                'created_at' => $n->created_at?->toIso8601String(),
                'type' => 'info',
            ];
        });

        return response()->json([
            'status' => 'success',
            'data' => $items,
        ]);
    }
}
