<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Notifications\Udalost;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use NotificationChannels\Fcm\FcmChannel;
use NotificationChannels\Fcm\FcmMessage;
use NotificationChannels\Fcm\Resources\Notification as FcmNotification;
use Seka\Portal\Core\Notifications\FirebaseCloudMessaging\Messages\Data\Enums\MessageDataMethodEnum;
use Seka\Portal\Core\Notifications\FirebaseCloudMessaging\Messages\Data\Enums\MessageDataTypeEnum;
use Seka\Portal\Modul\Terminy\Entities\Dtos\UdalostDTO;
use Seka\Portal\Modul\Terminy\Notifications\MAAG2MessageDataBuilder;

/**
 * Class ZverejnenaNovaUdalostNotifikaciaDB
 *
 * @package Seka\Portal\Modul\Terminy\Notifications\Udalost
 */
final class ZverejnenaNovaUdalostNotifikaciaDB extends Notification implements ShouldQueue
{
    use Queueable;

    public UdalostDTO $udalost;

    public function __construct(UdalostDTO $udalost)
    {
        $this->udalost = $udalost;
    }

    public function via(): array
    {
        return [
            'database',
            FcmChannel::class,
        ];
    }

    public function viaQueues(): array
    {
        return [
            FcmChannel::class => 'push-notifications-queue',
        ];
    }

    /**
     * @throws \Exception
     */
    public function toDatabase($notifiable): array
    {
        return $this->udalost->toArray();
    }

    public function toFcm($notifiable): FcmMessage
    {
        $unreadNotificationsCount = $notifiable->unreadNotifications()->count();
        $data = MAAG2MessageDataBuilder::make(
            MessageDataTypeEnum::INTERACTIVE,
            MessageDataMethodEnum::MAA_SHOW_USER_NOTIFICATION_SCREEN,
            ['id' => $this->udalost->id],
        );

        return FcmMessage::create()
            ->notification(
                FcmNotification::create()
                    ->title('Zverejnená nová udalosť')
                    ->body(
                        sprintf(
                            'Bola zverejnená udalosť %s',
                            $this->udalost->nazov,
                        ),
                    ),
            )
            ->data($data->toArray())
            ->custom([
                'android' => ['badge' => "$unreadNotificationsCount",],
                'apns' => ['payload' => ['aps' => ['badge' => "$unreadNotificationsCount",],],],
            ]);
    }
}
