<?php

namespace Modules\Announcement\Http\Controllers\Api;

use App\Http\Controllers\Api\ApiController;
use Illuminate\Http\Request;
use Modules\Announcement\Entities\Announcement;
use Modules\Announcement\Entities\Device;
use Modules\Announcement\Transformers\AnnouncementCollection;

class AllAnnouncementsController extends ApiController
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request)
    {
        $token = $request->header('X-Device-Id');

        $announcements = Announcement::query()
            ->withCount(['readDevices' => fn($q) => $q->where('token', $token)])
            ->active()
            ->latest()
            // ->take(config('api.limit_results_per_request', 100))
            ->get();

        if ($token) {
            $device = Device::where('token', $token)->first();
            $device?->announcements()->updateExistingPivot($announcements->pluck('id'), ['has_read' => true]);
        }

        return $this->json((new AnnouncementCollection($announcements))->toArray($request));
    }
}
