<?php

namespace App\Services;

use Pusher\Pusher;
use App\Models\Notification;
use Illuminate\Support\Facades\Log;

class NotificationPusherService
{
    protected $pusher;

    public function __construct()
    {
        $this->pusher = new Pusher(
            config('broadcasting.connections.pusher.key'),
            config('broadcasting.connections.pusher.secret'),
            config('broadcasting.connections.pusher.app_id'),
            [
                'cluster' => config('broadcasting.connections.pusher.options.cluster'),
                'useTLS' => config('broadcasting.connections.pusher.options.useTLS'),
            ]
        );
    }

    /**
     * Send real-time notification to specific user
     *
     * @param array $notificationData
     * @return bool
     */
    public function sendNotificationToUser(array $notificationData): bool
    {
        try {
            $channel = $this->getUserChannel($notificationData['receiver_id'], $notificationData['receiver_type']);
            
            $data = [
                'notification' => $notificationData,
                'timestamp' => now()->toISOString(),
                'type' => 'notification'
            ];

            $result = $this->pusher->trigger($channel, 'notification.received', $data);

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Send notification to multiple users
     *
     * @param array $notificationsData
     * @return array
     */
    public function sendNotificationsToUsers(array $notificationsData): array
    {
        $results = [];
         
        foreach ($notificationsData as $notificationData) {
            $results[] = [
                'receiver_id' => $notificationData['receiver_id'],
                'receiver_type' => $notificationData['receiver_type'],
                'success' => $this->sendNotificationToUser($notificationData)
            ];
        }
        
        return $results;
    }



    /**
     * Get user-specific channel name
     *
     * @param int $userId
     * @param string $userType
     * @return string
     */
    private function getUserChannel(int|string $userId, string $userType): string
    {
        $userId = trim((string) $userId);

        if ($userId === '') {
            throw new \InvalidArgumentException('Receiver ID must not be empty when triggering notifications.');
        }

        if ($userType === 'user') {
            return "private-user.{$userId}";
        } elseif ($userType === 'emp') {
            return "private-emp.{$userId}";
        }
        
        // Fallback for other types
        return "private-user.{$userId}";
    }






}
