<?php

namespace App\Console\Commands;

use App\Mail\CourseNudgeMail;
use App\Models\Enrollment;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class NudgeStalledLearners extends Command
{
    protected $signature = 'courses:nudge-stalled
                            {--force : Send even when the mailer is set to "log" (no SMTP)}';

    protected $description = 'Email a friendly reminder to learners who enrolled but stalled before finishing a course.';

    public function handle(): int
    {
        // Safety: with no real mail transport configured, sending would silently log
        // and still "spend" a nudge. Refuse unless explicitly forced.
        if (config('mail.default') === 'log' && ! $this->option('force')) {
            $this->warn('Mailer is "log" (no SMTP configured). No emails sent and no nudges spent.');
            $this->line('Configure SMTP in .env, then this runs automatically via the daily scheduler.');

            return self::SUCCESS;
        }

        $stalled = Enrollment::query()
            ->with(['user', 'course'])
            ->where('status', '!=', 'completed')
            ->where('progress', '<', 100)
            ->where('created_at', '<=', now()->subDays(5))   // give them a few days first
            ->where('nudge_count', '<', 3)                    // never more than 3 nudges
            ->where(function ($q) {
                $q->whereNull('last_nudged_at')
                    ->orWhere('last_nudged_at', '<=', now()->subDays(10)); // at most one per 10 days
            })
            ->get()
            ->filter(fn (Enrollment $e) => $e->user?->email && $e->course?->is_published);

        $sent = 0;

        foreach ($stalled as $enrollment) {
            Mail::to($enrollment->user->email)->send(new CourseNudgeMail($enrollment));

            $enrollment->forceFill([
                'nudge_count' => $enrollment->nudge_count + 1,
                'last_nudged_at' => now(),
            ])->save();

            $sent++;
        }

        $this->info("Nudged {$sent} stalled learner(s).");

        return self::SUCCESS;
    }
}
