<?php

namespace App\Console\Commands;

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

class DebugPresenceCommand extends Command
{
    protected $signature = 'presence:debug {profile_id} {guard=admin}';
    protected $description = 'Debug presence status for a specific profile';

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

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

        // Get the model
        $modelClass = $this->getModelClass($guard);
        $profile = $modelClass::find($profileId);

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

        $this->info("Profile: {$profile->name}");
        $this->info("---");

        // Check cache
        $cacheKey = "presence_{$guard}_{$profileId}";
        $cached = \Cache::get($cacheKey);
        $this->info("Cache Key: {$cacheKey}");
        $this->info("Cached Data: " . ($cached ? json_encode($cached) : 'NULL'));
        $this->info("---");

        // Check recent activities
        $this->info("Recent presence activities (last 10 minutes):");
        $activities = Activity::where('log_name', PresenceService::PRESENCE_ACTIVITY)
            ->where('subject_id', $profileId)
            ->where('subject_type', get_class($profile))
            ->where('properties->guard', $guard)
            ->where('created_at', '>=', now()->subMinutes(10))
            ->latest()
            ->get();

        if ($activities->isEmpty()) {
            $this->warn("No recent activities found");
        } else {
            foreach ($activities as $activity) {
                $props = is_string($activity->properties)
                    ? json_decode($activity->properties, true)
                    : $activity->properties;
                $status = $props['status'] ?? 'unknown';
                $this->line("- {$activity->created_at}: {$status} ({$activity->description})");
            }
        }
        $this->info("---");

        // Check PresenceService
        $presenceService = app(PresenceService::class);
        $isOnline = $presenceService->isUserOnline($profile, $guard);
        $lastSeen = $presenceService->getUserLastSeen($profile, $guard);

        $this->info("PresenceService->isUserOnline(): " . ($isOnline ? 'TRUE' : 'FALSE'));
        $this->info("PresenceService->getUserLastSeen(): " . ($lastSeen ? $lastSeen->toDateTimeString() : 'NULL'));
        $this->info("---");

        // Check authentication
        $isAuthenticated = auth($guard)->check() && auth($guard)->id() == $profileId;
        $this->info("Is authenticated in {$guard} guard: " . ($isAuthenticated ? 'TRUE' : 'FALSE'));

        return 0;
    }

    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;
    }
}
