<?php

declare(strict_types=1);

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

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\RegistraciaDTO;
use Seka\Portal\Modul\Terminy\Mail\Registracia\ZrusenaRegistraciaNaUdalostMail;
use Seka\Portal\Modul\Terminy\Notifications\MAAG2MessageDataBuilder;

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

    public RegistraciaDTO $registraciaDTO;

    public function __construct(RegistraciaDTO $registracia)
    {
        $this->registraciaDTO = $registracia;
    }

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

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

    public function toMail($notifiable): ZrusenaRegistraciaNaUdalostMail
    {
        return (new ZrusenaRegistraciaNaUdalostMail($this->registraciaDTO))
            ->to($notifiable);
    }

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

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

        return FcmMessage::create()
            ->notification(
                FcmNotification::create()
                    ->title('Zrušenie registrácie')
                    ->body(
                        sprintf(
                            'Vaša registrácia na udalosť %s bola zrušená',
                            $this->registraciaDTO->udalost->nazov,
                        ),
                    ),
            )
            ->data($data->toArray())
            ->custom([
                'android' => ['badge' => "$unreadNotificationsCount",],
                'apns' => ['payload' => ['aps' => ['badge' => "$unreadNotificationsCount",],],],
            ]);
    }
}
