<?php

namespace App\Console\Commands;

use App\Models\NotificationLog;
use App\Models\Setting;
use App\Services\NotificationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class ProcessScheduledNotifications extends Command
{
    protected $signature = 'notifications:send-scheduled';
    protected $description = 'Process and send scheduled notifications that are due';

    public function handle(): int
    {
        $lock = Cache::lock('notifications:send-scheduled:lock', 300);

        if (!$lock->get()) {
            $this->info('Another notifications sender process is still running. Skipping this run.');
            return 0;
        }

        try {
            $waDelay = (int) Setting::get('wa_send_delay_seconds', 10);
            $notificationService = app(NotificationService::class);

            // Get scheduled notifications that are due (limit to avoid OOM on large backlogs)
            $logs = NotificationLog::readyToSend()
                ->with(['application.applicant', 'application.jobListing'])
                ->orderBy('scheduled_at')
                ->limit(100)
                ->get();

            if ($logs->isEmpty()) {
                $this->info('No scheduled notifications to process.');
                return 0;
            }

            $this->info("Processing {$logs->count()} scheduled notifications...");

            $sent = 0;
            $failed = 0;
            $lastSentAt = null;
            $sendDelay = (int) Setting::get('notification_send_delay_seconds', 3);

            foreach ($logs as $log) {
                try {
                    // Delay between ALL sends (email & WA) to avoid bulk sending
                    if ($lastSentAt !== null) {
                        $elapsed = now()->diffInSeconds($lastSentAt);
                        $requiredDelay = ($log->channel === 'whatsapp') ? max($sendDelay, $waDelay) : $sendDelay;
                        if ($elapsed < $requiredDelay) {
                            sleep($requiredDelay - $elapsed);
                        }
                    }

                    $success = $notificationService->processScheduledLog($log);

                    if ($success) {
                        $sent++;
                        $lastSentAt = now();

                        // Auto-advance application status when stage notification is sent
                        $notificationService->advanceStatusForNotification($log);

                        $this->info("Sent {$log->channel} to {$log->recipient_name} ({$log->type})");
                    } else {
                        $failed++;
                        $this->error("Failed {$log->channel} to {$log->recipient_name}: {$log->error}");
                    }
                } catch (\Exception $e) {
                    $failed++;
                    $this->error("Exception for notification #{$log->id}: {$e->getMessage()}");
                    \Illuminate\Support\Facades\Log::error("ProcessScheduledNotifications exception: {$e->getMessage()}", [
                        'notification_id' => $log->id,
                    ]);
                }
            }

            $this->info("Done. Sent: {$sent}, Failed: {$failed}");
            return 0;
        } finally {
            optional($lock)->release();
        }
    }
}
