<?php

namespace App\Console\Commands;

use App\Services\BasketService;
use Illuminate\Console\Command;

class CleanupBasketsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'baskets:cleanup 
                            {--expired : Cleanup expired baskets only}
                            {--old : Cleanup old baskets only}
                            {--days=60 : Number of days for old baskets cleanup}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cleanup expired and old baskets';

    protected BasketService $basketService;

    public function __construct(BasketService $basketService)
    {
        parent::__construct();
        $this->basketService = $basketService;
    }

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $this->info(__('console.starting_basket_cleanup'));

        $expiredCount = 0;
        $oldCount = 0;

        // Süresi dolmuş sepetleri temizle
        if ($this->option('expired') || ! $this->option('old')) {
            $this->info(__('console.cleaning_expired_baskets'));
            $expiredCount = $this->basketService->cleanupExpiredBaskets();
            $this->info("Cleaned up {$expiredCount} expired baskets.");
        }

        // Eski sepetleri temizle
        if ($this->option('old') || ! $this->option('expired')) {
            $days = (int) $this->option('days');
            $this->info("Cleaning up baskets older than {$days} days...");
            $oldCount = $this->basketService->cleanupOldBaskets($days);
            $this->info("Cleaned up {$oldCount} old baskets.");
        }

        $totalCount = $expiredCount + $oldCount;

        if ($totalCount > 0) {
            $this->info("Total cleanup completed: {$totalCount} baskets removed.");
        } else {
            $this->info(__('console.no_baskets_cleaned'));
        }

        // İstatistikleri göster
        $stats = $this->basketService->getStatistics();
        $this->table(
            ['Metric', 'Count'],
            [
                ['Total Baskets', $stats['total']],
                ['Active Baskets', $stats['active']],
                ['Expired Baskets', $stats['expired']],
                ['Anonymous Baskets', $stats['anonymous']],
                ['Client Baskets', $stats['client']],
                ['Recent Activity (7 days)', $stats['recent_activity']],
                ['Old Baskets (30+ days)', $stats['old']],
            ]
        );

        return Command::SUCCESS;
    }
}
