<?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\AnnouncementResource;
use Symfony\Component\HttpFoundation\Response;

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

        $announcement = Announcement::query()
            ->withCount(['readDevices' => fn($q) => $q->where('token', $token)])
            ->where('id', Announcement::keyFromHashId($hash))
            ->active()
            ->first();

        if (!$announcement) {
            return $this->jsonError(Response::HTTP_NOT_FOUND, __('Announcement not found or invalid.'), reference_code: 'A001');
        }

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

        return $this->json((new AnnouncementResource($announcement))->toArray($request));
    }
}
