<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Models\Committee;
use App\Models\WorkGroup;
use App\Models\MsgraphPendingChange;
use App\Services\MicrosoftGraph\UserMembershipTracker;
use Illuminate\Console\Command;

class TestMembershipTracking extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:membership-tracking';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test the membership tracking system for Microsoft Graph sync';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('🧪 Testing Membership Tracking System');
        $this->newLine();

        // Get statistics
        $activeUsers = User::where('state', 'active')->count();
        $publishedCommittees = Committee::full()->where('status', 'published')->count();
        $publishedWorkgroups = WorkGroup::full()->where('status', 'published')->count();
        $pendingChanges = MsgraphPendingChange::unprocessed()->count();

        $this->info("📊 System Status:");
        $this->line("  - Active users: {$activeUsers}");
        $this->line("  - Published committees: {$publishedCommittees}");
        $this->line("  - Published workgroups: {$publishedWorkgroups}");
        $this->line("  - Pending changes: {$pendingChanges}");
        $this->newLine();

        // Get a test user
        $testUser = User::with(['committees', 'workGroups'])
            ->where('state', 'active')
            ->first();

        if (!$testUser) {
            $this->error('❌ No active users found for testing');
            return 1;
        }

        $this->info("👤 Test User: {$testUser->name} {$testUser->last_name} (ID: {$testUser->id})");
        $this->line("  - Current committees: " . $testUser->committees->count());
        $this->line("  - Current workgroups: " . $testUser->workGroups->count());
        $this->newLine();

        // Get a test committee
        $testCommittee = Committee::full()
            ->where('status', 'published')
            ->first();

        if (!$testCommittee) {
            $this->error('❌ No published committees found for testing');
            return 1;
        }

        $this->info("🏛️ Test Committee: {$testCommittee->title} (ID: {$testCommittee->id})");
        $this->newLine();

        // Test the tracking by simulating a join
        $this->info('🔄 Testing user join tracking...');

        try {
            UserMembershipTracker::trackUserJoined($testCommittee, $testUser, 'to');
            $this->info('✅ Successfully tracked user join');
        } catch (\Exception $e) {
            $this->error('❌ Failed to track user join: ' . $e->getMessage());
            return 1;
        }

        // Check if the change was recorded
        $newPendingChanges = MsgraphPendingChange::unprocessed()->count();
        $this->info("📈 Pending changes after test: {$newPendingChanges}");

        // Show recent changes
        $recentChanges = MsgraphPendingChange::unprocessed()
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        if ($recentChanges->count() > 0) {
            $this->info('📋 Recent pending changes:');
            foreach ($recentChanges as $change) {
                $this->line("  - {$change->action} | User: {$change->user_name} | Model: {$change->model_title} | Created: {$change->created_at}");
            }
        }

        $this->newLine();
        $this->info('✅ Membership tracking test completed successfully!');

        return 0;
    }
}
