<?php

namespace App\Console\Commands;

use App\Models\ForumThread;
use Carbon\Carbon;
use Illuminate\Console\Command;

class AutoLockInactiveThreadsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'forum:autolock-threads 
                            {--dry-run : Run without making changes}
                            {--detailed : Show detailed output}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Automatically lock forum threads that have been inactive for the configured number of days';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Check if auto-locking is enabled
        if (!config_value('forum_autolock_thread')) {
            $this->info('Forum thread auto-locking is disabled.');
            return Command::SUCCESS;
        }

        $autolockDays = config_value('forum_autolock_thread_days');
        
        if (!$autolockDays || $autolockDays <= 0) {
            $this->error('Invalid forum_autolock_thread_days configuration value.');
            return Command::FAILURE;
        }

        $cutoffDate = Carbon::now()->subDays($autolockDays);
        $isDryRun = $this->option('dry-run');
        $isDetailed = $this->option('detailed');

        $this->info("Checking for threads inactive since: {$cutoffDate->format('Y-m-d H:i:s')}");
        
        if ($isDryRun) {
            $this->warn('DRY RUN MODE - No changes will be made');
        }

        $threadsToLock = ForumThread::query()
            ->where('is_locked', false)
            ->where(function ($query) use ($cutoffDate) {
                $query->where('last_activity_at', '<', $cutoffDate)
                    ->orWhere(function ($subQuery) use ($cutoffDate) {
                        $subQuery->whereNull('last_activity_at')
                                ->where('created_at', '<', $cutoffDate);
                    });
            })
            ->with(['posts' => function ($query) {
                $query->latest()->limit(1);
            }]);

        $threadsToLock = $threadsToLock->get()->filter(function ($thread) use ($cutoffDate) {
            $lastPost = $thread->lastPost();
            
            if ($lastPost) {
                return $lastPost->created_at < $cutoffDate;
            }
            
            return $thread->created_at < $cutoffDate;
        });

        $threadCount = $threadsToLock->count();

        if ($threadCount === 0) {
            $this->info('No threads found that need to be auto-locked.');
            return Command::SUCCESS;
        }

        $this->info("Found {$threadCount} thread(s) to auto-lock:");

        $lockedCount = 0;

        foreach ($threadsToLock as $thread) {
            $lastPost = $thread->lastPost();
            $lastActivityDate = $lastPost ? $lastPost->created_at : $thread->created_at;
            $daysInactive = Carbon::now()->diffInDays($lastActivityDate);

            if ($isDetailed || $isDryRun) {
                $this->line("- Thread ID {$thread->id}: \"{$thread->title}\" (inactive for {$daysInactive} days)");
            }

            if (!$isDryRun) {
                try {
                    $thread->update([
                        'is_locked' => true,
                        'updated_at' => now()
                    ]);
                    $lockedCount++;
                } catch (\Exception $e) {
                    $this->error("Failed to lock thread ID {$thread->id}: {$e->getMessage()}");
                }
            }
        }

        if ($isDryRun) {
            $this->info("DRY RUN: Would have locked {$threadCount} thread(s).");
        } else {
            $this->info("Successfully locked {$lockedCount} thread(s).");
            
            if ($lockedCount < $threadCount) {
                $this->warn("Failed to lock " . ($threadCount - $lockedCount) . " thread(s). Check the logs for details.");
            }
        }

        return Command::SUCCESS;
    }
}