<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Libs\Services\FcmService;
use App\Services\FcmMessageDataService;
use App;
use Throwable;
use Illuminate\Support\Facades\Log;
use App\Models\Exhibition;
use Illuminate\Support\Carbon;

class ProcessTestNotification implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected FcmService $fcmService;
    protected FcmMessageDataService $fcmDataService;
    public const TOPIC = 'testing';
    public const QUEUE = 'testing';

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {

        $this->onQueue(static::QUEUE);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(FcmService $fcmService, FcmMessageDataService $fcmDataService)
    {

        $this->fcmService     = $fcmService;
        $this->fcmDataService = $fcmDataService;
        $messageId            = null;
        $data                 = [
            'topic' => static::TOPIC
        ];

        //for testing purposes we will get a random published exhibition and add it to the data
        $exhibition = Exhibition::full()
            ->where('status', 'published')
            ->where('date_to', '<=', Carbon::now())
            ->orderBy('id', 'ASC')
            ->first();
        if ($exhibition) {
            $data['id']   = $exhibition->id;
            $data['type'] = 'exposicao';
        }

        $body                 = 'This is a Contemporânea FCM test message - ' . date('Y-m-d H:i:s');
        $title                = 'Contemporanea test message';
        $title                = "\u{1F37E}" . ' ' . $title;
        $message              = $this->fcmService->getTopicMessageStructure(static::TOPIC, $title, $body, $data);

        //send the message to the test topic
        try {
            $messageId = $this->fcmService->sendMessageToTopic($message);
            if ($messageId) {
                $messageContent = $message;
                Log::info('The test notification was sent with the message id ' . $messageId);
            }
        } catch (Throwable $t) {
            Log::error('Error sending testing message: ' . $t->getMessage());
        }

        if ($messageId) {
            $this->fcmDataService->addFcmTopicMessage('testing', $messageId, $messageContent);
        }
    }
}
