<?php

namespace App\Console\Commands;

use App\Services\PresenceService;
use Illuminate\Console\Command;
use Spatie\Activitylog\Models\Activity;

class ClearPresenceCommand extends Command
{
    protected $signature = 'presence:clear {profile_id?} {guard?}';
    protected $description = 'Clear presence cache and set profile offline';

    public function handle()
    {
        $profileId = $this->argument('profile_id');
        $guard = $this->argument('guard');

        if ($profileId && $guard) {
            // Clear specific profile
            $this->clearSpecificProfile($profileId, $guard);
        } else {
            // Clear all presence data
            $this->clearAllPresence();
        }

        return 0;
    }

    protected function clearSpecificProfile($profileId, $guard)
    {
        $this->info("Clearing presence for Profile ID: {$profileId}, Guard: {$guard}");

        $modelClass = $this->getModelClass($guard);
        $profile = $modelClass::find($profileId);

        if (!$profile) {
            $this->error("Profile not found!");
            return;
        }

        // Set offline
        $presenceService = app(PresenceService::class);
        $presenceService->setUserOffline($profile, $guard);

        // Clear caches
        \Cache::forget("presence_{$guard}_{$profileId}");
        \Cache::forget("presence_last_update_{$guard}_{$profileId}");
        \Cache::forget("online_users_{$guard}_" . PresenceService::ONLINE_THRESHOLD_MINUTES);

        $this->info("✓ Presence cleared for {$profile->name}");
    }

    protected function clearAllPresence()
    {
        $this->info("Clearing ALL presence data...");

        $guards = ['web', 'admin', 'bank', 'organization'];

        foreach ($guards as $guard) {
            // Clear online users cache
            \Cache::forget("online_users_{$guard}_" . PresenceService::ONLINE_THRESHOLD_MINUTES);
            $this->line("✓ Cleared online users cache for {$guard} guard");
        }

        // Clear all presence cache keys
        $cacheKeys = \Cache::getRedis()->keys('*presence_*');
        foreach ($cacheKeys as $key) {
            // Remove the Redis prefix from the key
            $cleanKey = str_replace(\Cache::getRedis()->getOptions()->prefix, '', $key);
            \Cache::forget($cleanKey);
        }

        $this->info("✓ Cleared all presence cache keys");

        // Optionally mark all users as offline in activity log
        if ($this->confirm('Do you want to mark all users as offline in the activity log?', false)) {
            $presenceService = app(PresenceService::class);

            // Get all recent online activities
            $recentActivities = Activity::where('log_name', PresenceService::PRESENCE_ACTIVITY)
                ->where('properties->status', 'online')
                ->where('created_at', '>=', now()->subMinutes(60))
                ->with('subject')
                ->get();

            foreach ($recentActivities as $activity) {
                if ($activity->subject) {
                    $props = is_string($activity->properties)
                        ? json_decode($activity->properties, true)
                        : $activity->properties;
                    $guard = $props['guard'] ?? 'web';
                    $presenceService->setUserOffline($activity->subject, $guard);
                    $this->line("  - Set {$activity->subject->name} offline ({$guard})");
                }
            }

            $this->info("✓ Marked all users as offline");
        }

        $this->info("Done!");
    }

    protected function getModelClass($guard)
    {
        $map = [
            'web' => \App\Models\User::class,
            'admin' => \App\Models\Admin::class,
            'bank' => \App\Models\Bank::class,
            'organization' => \App\Models\Organization::class,
        ];

        return $map[$guard] ?? \App\Models\User::class;
    }
}
