<?php

namespace App\Services;

use App\Models\NotifyTemplate;

class NotificationTemplateService
{
    /**
     * Get the template data by code.
     *
     * @param string $code
     * @return array|null
     */
    public function getTemplateData(string $code): ?array
    {
        // Use firstOrFail if you want an exception when not found, otherwise use first()
        $template = NotifyTemplate::where('code', $code)->first();

        // Return the template data
        return [
            'subject' => $template->subject,
            'mail_message' => $template->mail_message,
            'push_message' => $template->push_message,
            'via' => $this->getChannels($template),
        ];
    }

    /**
     * Get the channels (via) for the notification based on status fields.
     *
     * @param NotifyTemplate $template
     * @return array
     */
    private function getChannels(NotifyTemplate $template): array
    {
        $channels = [];

        // Add mail if mail_status is true
        if ($template->mail_status) {
            $channels[] = 'mail';
        }

        // Check push_status and add appropriate channels
        if ($template->push_status) {
            $channels[] = 'database';

            // Check pusher status only once
            $pusherStatus = pluginCredentials('pusher')['status'] ?? false;
            if ($pusherStatus) {
                $channels[] = 'broadcast';
            }
        }

        return $channels;
    }
}
