<?php

namespace App\Traits;

use App\Jobs\SendFcmMessageToTopic;
use App\Libs\Services\FcmService;
use Throwable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

trait FcmSubscribable
{

    public static function bootFcmSubscribable()
    {

        static::created(function ($item) {

            if (!FcmService::areFcmNotificationsActive()) {
                return;
            }

            /** @var Request $request */
            $request = request();

            $sendPushNotification = $request->input('send_push_messages');

            if (!$item->status === 'published') {
                return;
            }

            if (!$sendPushNotification) {
                return;
            }

            //get the associated topic
            $topic = FcmService::getFcmTopicFromModel($item);
            if (empty($topic)) {
                return;
            }


            //dispatch the job to send the messages to the topic
            if (DB::transactionLevel() > 0) {
                DB::afterCommit(function () use ($item, $topic) {
                    SendFcmMessageToTopic::dispatch($item, $topic);
                });
            } else {
                SendFcmMessageToTopic::dispatch($item, $topic);
            }
        });
    }
}
