<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\EmailMessage;
use App\Jobs\SendEmailMessage;

class DispatchDueEmails extends Command
{
    protected $signature = 'emails:dispatch-due';
    protected $description = 'Invia le email programmate giunte a scadenza';

    public function handle()
    {
        app(\App\Http\Middleware\TenantMiddleware::class)->setupTenantConnection();

        EmailMessage::where('status', 'scheduled')
            ->where('schedule_at', '<=', now())
            ->chunkById(100, function ($chunk) {
                foreach ($chunk as $msg) {
                    dispatch(new SendEmailMessage($msg->id));
                }
            });

        return Command::SUCCESS;
    }
}
