<?php

namespace App\Console\Commands;

use App\Models\Committee;
use App\Models\WorkGroup;
use App\Models\MsgraphModelChange;
use App\Services\MicrosoftGraph\ModelChangeTrackingService;
use Illuminate\Console\Command;

class TestModelChangeTracking extends Command
{
    protected $signature = 'test:model-change-tracking';
    protected $description = 'Test the model change tracking system for committees and workgroups';

    protected $trackingService;

    public function __construct(ModelChangeTrackingService $trackingService)
    {
        parent::__construct();
        $this->trackingService = $trackingService;
    }

    public function handle()
    {
        $this->info('🧪 Testing model change tracking system...');

        // Test 1: Committee Status Change
        $this->info("\n🔬 Test 1: Committee status change tracking");

        $committee = Committee::where('type', 'standard')->first();
        if (!$committee) {
            $this->error('❌ No standard committee found for testing');
            return;
        }

        $this->info("📋 Using Committee: {$committee->title} (ID: {$committee->id})");

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

        // Simulate a status change
        $oldStatus = $committee->status ?? 'draft';
        $newStatus = $oldStatus === 'published' ? 'draft' : 'published';

        $this->info("🔄 Simulating status change from '{$oldStatus}' to '{$newStatus}'");
        $this->trackingService->trackCommitteeStatusChanged($committee, $oldStatus, $newStatus);

        // Count pending changes after
        $changesAfter = MsgraphModelChange::unprocessed()->count();
        $this->info("📊 Pending model changes after: {$changesAfter}");

        if ($changesAfter > $changesBefore) {
            $this->info("✅ Status change tracked successfully!");

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

            if ($latestChange) {
                $this->info("📝 Latest change:");
                $this->info("   - Action: {$latestChange->action}");
                $this->info("   - Model: {$latestChange->model_title}");
                $this->info("   - Old Status: {$latestChange->old_status}");
                $this->info("   - New Status: {$latestChange->new_status}");
            }
        } else {
            $this->error("❌ No status change was tracked");
        }

        // Test 2: Committee Title Change
        $this->info("\n🔬 Test 2: Committee title change tracking");

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

        // Simulate a title change
        $oldTitle = $committee->title ?? 'Old Title';
        $newTitle = 'Test Committee Title - ' . now()->format('H:i:s');

        $this->info("📝 Simulating title change from '{$oldTitle}' to '{$newTitle}'");
        $this->trackingService->trackCommitteeTitleChanged($committee, $oldTitle, $newTitle, 'en');

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

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

            // Show the latest change
            $latestTitleChange = MsgraphModelChange::unprocessed()
                ->where('action', 'title_changed')
                ->latest()
                ->first();

            if ($latestTitleChange) {
                $this->info("📝 Latest title change:");
                $this->info("   - Action: {$latestTitleChange->action}");
                $this->info("   - Model: {$latestTitleChange->model_title}");
                $this->info("   - Old Title: {$latestTitleChange->old_title}");
                $this->info("   - New Title: {$latestTitleChange->new_title}");
                $this->info("   - Language: {$latestTitleChange->language}");
            }
        } else {
            $this->error("❌ No title change was tracked");
        }

        // Test 3: WorkGroup tracking
        $this->info("\n🔬 Test 3: WorkGroup tracking");

        $workGroup = WorkGroup::first();
        if ($workGroup) {
            $this->info("📋 Using WorkGroup: {$workGroup->title} ({$workGroup->id})");

            $changesBefore3 = MsgraphModelChange::unprocessed()->count();

            // Test workgroup status change
            $oldWgStatus = $workGroup->status ?? 'draft';
            $newWgStatus = $oldWgStatus === 'published' ? 'draft' : 'published';

            $this->info("🔄 Simulating WorkGroup status change from '{$oldWgStatus}' to '{$newWgStatus}'");
            $this->trackingService->trackWorkGroupStatusChanged($workGroup, $oldWgStatus, $newWgStatus);

            $changesAfter3 = MsgraphModelChange::unprocessed()->count();

            if ($changesAfter3 > $changesBefore3) {
                $this->info("✅ WorkGroup status change tracked successfully!");
            } else {
                $this->error("❌ No WorkGroup status change was tracked");
            }
        } else {
            $this->info("ℹ️ No WorkGroup found for testing");
        }

        // Summary
        $this->info("\n📊 Test Summary:");
        $totalChanges = MsgraphModelChange::unprocessed()->count();
        $this->info("   📝 Total unprocessed model changes: {$totalChanges}");

        if ($totalChanges > 0) {
            $this->info("   📋 Recent changes:");
            $recentChanges = MsgraphModelChange::unprocessed()
                ->latest()
                ->take(5)
                ->get();

            foreach ($recentChanges as $change) {
                $this->info("     - {$change->action} on {$change->model_title} ({$change->created_at->format('H:i:s')})");
            }
        }

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