<?php

namespace App\Console\Commands;

use App\Models\MailQueue;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('mail:cleanup')]
#[Description('Command description')]
class CleanMailQueue extends Command
{
    /**
     * Execute the console command.
     */
    public function handle()
    {
        // 🔥 SENT (1 Tag)
        $sent = MailQueue::where('status', 'sent')
            ->where('sent_at', '<', now()->subDay())
            ->delete();

        // 🔥 FAILED (7 Tage)
        $failed = MailQueue::where('status', 'failed')
            ->where('updated_at', '<', now()->subDays(7))
            ->delete();

        // 🔥 CANCELED (2 Tage)
        $canceled = MailQueue::where('status', 'canceled')
            ->where('updated_at', '<', now()->subDays(2))
            ->delete();

        // 🔥 STUCK PROCESSING → zurücksetzen
        $recovered = MailQueue::where('status', 'processing')
            ->where('updated_at', '<', now()->subMinutes(10))
            ->update([
                'status' => 'pending',
                'available_at' => now(),
            ]);


        $this->info("Sent deleted: $sent");
        $this->info("Failed deleted: $failed");
        $this->info("Canceled deleted: $canceled");
        $this->info("Recovered jobs: $recovered");
    }
}
