<?php

declare(strict_types=1);

namespace App\Notifications\Push;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use NotificationChannels\Fcm\FcmMessage;
use NotificationChannels\Fcm\Resources\AndroidConfig;
use NotificationChannels\Fcm\Resources\AndroidNotification;
use NotificationChannels\Fcm\Resources\ApnsConfig;
use Seka\Portal\Core\Notifications\FirebaseCloudMessaging\Channels\FcmChannel;
use Seka\Portal\Core\Notifications\FirebaseCloudMessaging\Messages\Data\Enums\MessageDataMethodEnum;
use Seka\Portal\Core\Notifications\FirebaseCloudMessaging\Messages\Data\Enums\MessageDataSourceEnum;
use Seka\Portal\Core\Notifications\FirebaseCloudMessaging\Messages\Data\Enums\MessageDataTypeEnum;
use Seka\Portal\Core\Notifications\FirebaseCloudMessaging\Messages\MessageDataBuilder;

/**
 * Class MAAISEKUserNotificationsCountPushNotification
 *
 * @package App\Notifications\Push
 */
final class MAAISEKUserNotificationsCountPushNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * @return string[]
     */
    public function via($notifiable): array
    {
        return [
            FcmChannel::class,
        ];
    }

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

    /**
     * @throws \NotificationChannels\Fcm\Exceptions\CouldNotSendNotification
     */
    public function toFcm($notifiable): FcmMessage
    {
        $unreadNotificationsCount = $notifiable->unreadNotifications()->count();
        $data = MessageDataBuilder::make(
            MessageDataSourceEnum::PORTAL_WEB(),
            MessageDataTypeEnum::NON_INTERACTIVE(),
            MessageDataMethodEnum::MAA_SET_COUNT_OF_UNREAD_USER_NOTIFICATIONS(),
        );

        $data = array_merge($data->toArray(), ['unreadNotificationsCount' => "$unreadNotificationsCount"]);

        return FcmMessage::create()
            ->setData($data)
            ->setAndroid(
                AndroidConfig::create()->setNotification(
                    AndroidNotification::create()->setNotificationCount($unreadNotificationsCount),
                ),
            )
            ->setApns(ApnsConfig::create()->setPayload(['aps' => ['badge' => $unreadNotificationsCount]]));
    }
}
