<?php

namespace App\Console\Commands;

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

class TestServiceBasedTracking extends Command
{
    protected $signature = 'test:service-tracking';
    protected $description = 'Test the service-based membership tracking system';

    protected $userMembershipService;

    public function __construct(UserMembershipService $userMembershipService)
    {
        parent::__construct();
        $this->userMembershipService = $userMembershipService;
    }

    public function handle()
    {
        $this->info('🧪 Testing service-based membership tracking...');

        // Find a test user and committee
        $user = User::where('state', 'active')->first();
        $committee = Committee::full()->where('status', 'published')->first();

        if (!$user || !$committee) {
            $this->error('❌ No active user or published committee found for testing');
            return;
        }

        $this->info("📋 Using User: {$user->name} (ID: {$user->id})");
        $this->info("📋 Using Committee: {$committee->title} (ID: {$committee->id})");        // Test 1: Individual detach
        $this->info("\n🔬 Test 1: Individual detach with tracking");

        // Check if user is already attached to committee
        $isAlreadyAttached = $user->committees()->where('committee_id', $committee->id)->exists();

        if (!$isAlreadyAttached) {
            // Attach the user to the committee
            $user->committees()->attach($committee->id, ['type' => 'to']);
            $this->info("✅ User attached to committee");
        } else {
            $this->info("ℹ️ User already attached to committee");
        }

        // Count pending changes before detach
        $changesBefore = MsgraphPendingChange::unprocessed()->count();
        $this->info("📊 Pending changes before detach: {$changesBefore}");

        // Check if user is currently attached to committee before detaching
        $currentAttachment = $user->committees()->where('committee_id', $committee->id)->first();

        if ($currentAttachment) {
            $this->info("ℹ️ User is currently attached with type: {$currentAttachment->pivot->type}");

            // Use service to detach
            $this->userMembershipService->detachUserFromCommittee($user, $committee->id);
            $this->info("✅ User detached using service");
        } else {
            $this->info("ℹ️ User is not currently attached to committee, skipping detach test");
        }        // Count pending changes after detach
        $changesAfter = MsgraphPendingChange::unprocessed()->count();
        $this->info("📊 Pending changes after detach: {$changesAfter}");

        if ($currentAttachment && $changesAfter > $changesBefore) {
            $this->info("✅ Change tracked successfully!");

            // Show the latest change
            $latestChange = MsgraphPendingChange::unprocessed()
                ->latest()
                ->first();

            if ($latestChange) {
                $this->info("📝 Latest change:");
                $this->info("   - Action: {$latestChange->action}");
                $this->info("   - User: {$latestChange->user->name}");
                $this->info("   - Model: {$latestChange->model_title}");
                $this->info("   - Old Type: {$latestChange->old_membership_type}");
            }
        } elseif ($currentAttachment) {
            $this->error("❌ No change was tracked after detach");
        } else {
            $this->info("ℹ️ No detach performed, so no change tracking expected");
        }        // Test 2: Sync with tracking
        $this->info("\n🔬 Test 2: Sync with tracking");

        $changesBefore2 = MsgraphPendingChange::unprocessed()->count();
        $this->info("📊 Pending changes before sync: {$changesBefore2}");

        // First, ensure user is not attached to avoid duplicates
        $user->committees()->detach($committee->id);

        // Now sync with the committee
        $this->userMembershipService->syncUserCommittees($user, [
            $committee->id => ['type' => 'cc']
        ]);
        $this->info("✅ User synced to committee as to");

        $changesAfter2 = MsgraphPendingChange::unprocessed()->count();
        $this->info("📊 Pending changes after sync: {$changesAfter2}");

        if ($changesAfter2 > $changesBefore2) {
            $this->info("✅ Sync change tracked successfully!");

            // Show the latest change
            $latestSyncChange = MsgraphPendingChange::unprocessed()
                ->latest()
                ->first();

            if ($latestSyncChange) {
                $this->info("📝 Latest sync change:");
                $this->info("   - Action: {$latestSyncChange->action}");
                $this->info("   - User: {$latestSyncChange->user->name}");
                $this->info("   - Model: {$latestSyncChange->model_title}");
                $this->info("   - New Type: {$latestSyncChange->new_membership_type}");
            }
        } else {
            $this->error("❌ No sync change was tracked");
        }

        // Clean up: Remove the test user from the committee
        $this->info("\n🧹 Cleaning up test data...");
        $user->committees()->detach($committee->id);
        $this->info("✅ Test user detached from committee");

        $this->info("\n🎉 Service-based tracking test completed!");
    }
}
