<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\EmailMessage;
use App\Jobs\SendEmailMessage;
use DateTimeZone;
use Illuminate\Foundation\Auth\User;

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

    public function handle()
    {
        $users = User::whereNotNull('tenant_host')
            ->whereNotNull('tenant_database')
            ->whereNotNull('tenant_username')
            ->whereNotNull('tenant_password')
            ->get([
                'id',
                'tenant_host',
                'tenant_database',
                'tenant_username',
                'tenant_password',
            ]);

        if ($users->isEmpty()) {
            $this->warn('Nessun utente con info di database trovata.');
            return Command::SUCCESS;
        }

        $tenants = $users->unique(function ($u) {
            return $u->tenant_host . '|' . $u->tenant_database . '|' . $u->tenant_username;
        });

        foreach ($tenants as $userTenant) {
            $this->info("Processo tenant db={$userTenant->tenant_database} (user id={$userTenant->id})");

            app(\App\Http\Middleware\TenantMiddleware::class)->setupTenantConnection($userTenant);

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

        return Command::SUCCESS;
    }
}
