<?php

namespace App\Console\Commands;

use App\Models\Mailing;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ProcessScheduledMailings extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mailings:process-scheduled
                            {--dry-run : Show what would be sent without actually sending}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process scheduled mailings that are ready to be sent';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $dryRun = $this->option('dry-run');

        $this->info('Looking for scheduled mailings ready to be sent...');

        // Find mailings that are scheduled and due to be sent
        $scheduledMailings = Mailing::where('status', 'scheduled')
            ->where('scheduled_at', '<=', now())
            ->get();

        if ($scheduledMailings->isEmpty()) {
            $this->info('No scheduled mailings ready to be sent.');
            return 0;
        }

        $this->info("Found {$scheduledMailings->count()} scheduled mailing(s) ready to be sent:");

        foreach ($scheduledMailings as $mailing) {
            $this->line("- Mailing ID {$mailing->id}: '{$mailing->title}' (scheduled for {$mailing->scheduled_at})");

            if (!$dryRun) {
                try {
                    // Update status to sending
                    $mailing->update(['status' => 'sending']);

                    // Dispatch the locale-specific jobs
                    $mailing->dispatchLocaleSpecificJobs();

                    $this->info("  ✓ Dispatched jobs for mailing ID {$mailing->id}");

                } catch (\Exception $e) {
                    $this->error("  ✗ Failed to dispatch mailing ID {$mailing->id}: {$e->getMessage()}");
                    Log::error("Failed to dispatch scheduled mailing {$mailing->id}", [
                        'mailing_id' => $mailing->id,
                        'error' => $e->getMessage(),
                        'trace' => $e->getTraceAsString()
                    ]);
                }
            } else {
                $this->line("  (dry run - would dispatch jobs for mailing ID {$mailing->id})");
            }
        }

        if ($dryRun) {
            $this->info('Dry run completed. Use without --dry-run to actually send the mailings.');
        } else {
            $this->info('Scheduled mailings processing completed.');
        }

        return 0;
    }
}