<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Modules\Announcement\Entities\Announcement;
use Modules\Announcement\Entities\Device;
use Symfony\Component\HttpFoundation\Response;

class DeviceRegisterController extends ApiController
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => ['nullable', 'string', 'max:100'],
            'info' => ['nullable', 'string'],
            'fcm' => ['nullable', 'string'],
            'token' => ['required', 'string'],
        ], $this->addValidationErrorCode());

        if ($validator->fails()) {
            return $this->handleValidationResponse($validator->errors()->toArray());
        }

        DB::beginTransaction();

        try {
            $attr = ['ip_address' => $request->ip()];

            if ($request->filled('name')) {
                $attr['name'] = $request->input('name');
            }

            if ($request->filled('fcm')) {
                $attr['fcm_token'] = $request->input('fcm');
            }

            if ($request->filled('info')) {
                $attr['info'] = json_decode($request->input('info', ''));
            }

            $device = Device::updateOrCreate(['token' => $request->input('token')], $attr);

            $announcements = Announcement::pluck('id');
            $announcements->reject(fn($v) => $device->readAnnouncements()->pluck('id')->contains($v));

            $device->announcements()->sync($announcements, ['has_read' => false]);

            DB::commit();

            if ($device->fcm_token) {
                Device::subscribeTopicFCM();
            }

            return $this->json([
                // 'type' => 'register',
                'hash' => $device->hash_id,
                // 'dot' => $device->unreadAnnouncements()->active()->count(),
            ], Response::HTTP_CREATED);
        } catch (\Exception $e) {
            DB::rollBack();

            // report($e);

            return $this->jsonError(Response::HTTP_UNPROCESSABLE_ENTITY, $e->getMessage());
        }
    }
}
