<?php

namespace App\Observers;

use App\Models\Notification;
use App\Services\PushNotificationService;

class NotificationObserver
{
    protected $pushService;

    public function __construct(PushNotificationService $pushService)
    {
        $this->pushService = $pushService;
    }

    /**
     * Handle the Notification "created" event.
     *
     * @param  \App\Models\Notification  $notification
     * @return void
     */
    public function created(Notification $notification)
    {
        // Send push notification asynchronously
        // Using dispatch with afterResponse to avoid blocking the request
        try {
            dispatch(function () use ($notification) {
                $this->pushService->sendNotificationCreated($notification);
            })->afterResponse();
        } catch (\Exception $e) {
            // If dispatch fails, try to send in background using exec
            \Log::info('Dispatch failed, attempting background send: ' . $e->getMessage());
            try {
                // Use a simple background process for sending
                if (function_exists('exec') && !\App::environment('testing')) {
                    $command = sprintf(
                        'php %s/artisan notification:push %d > /dev/null 2>&1 &',
                        base_path(),
                        $notification->id
                    );
                    exec($command);
                } else {
                    // Fallback: send synchronously but log it
                    $this->pushService->sendNotificationCreated($notification);
                }
            } catch (\Exception $ex) {
                \Log::error('Failed to send push notification: ' . $ex->getMessage());
            }
        }
    }
}

