<?php

namespace App\Console\Commands;

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

class TestSmartSync extends Command
{
    protected $signature = 'msgraph:test-smart-sync
                            {--dry-run : Show what would be synced without making changes}
                            {--create-test-data : Create some test changes to process}';

    protected $description = 'Test the smart sync system with specific change tracking';

    protected $smartSyncService;

    public function __construct(SmartSyncService $smartSyncService)
    {
        parent::__construct();
        $this->smartSyncService = $smartSyncService;
    }

    public function handle()
    {
        $dryRun = $this->option('dry-run');
        $createTestData = $this->option('create-test-data');

        $this->info('🧪 Testing Smart Sync System');
        $this->newLine();

        try {
            if ($createTestData) {
                $this->createTestData();
                $this->newLine();
            }

            $this->info('📊 Current pending changes:');
            $counts = $this->smartSyncService->getPendingChangeCounts();
            $this->table(
                ['Change Type', 'Pending Count'],
                [
                    ['Membership Changes', $counts['membership_changes']],
                    ['Model Changes', $counts['model_changes']],
                    ['Total', $counts['membership_changes'] + $counts['model_changes']]
                ]
            );

            if ($counts['membership_changes'] + $counts['model_changes'] === 0) {
                $this->info('✅ No pending changes found.');
                if (!$createTestData) {
                    $this->info('💡 Use --create-test-data to create some test changes');
                }
                return 0;
            }

            $this->newLine();
            $this->info('🧠 Testing smart sync...');

            $results = $this->smartSyncService->processAllPendingChanges($dryRun);

            $this->newLine();
            $this->info('📋 Test Results:');
            $this->table(
                ['Change Type', 'Processed'],
                [
                    ['Membership Changes', $results['membership_changes']],
                    ['Model Changes', $results['model_changes']],
                    ['Total', $results['membership_changes'] + $results['model_changes']]
                ]
            );

            if (!empty($results['errors'])) {
                $this->newLine();
                $this->error('❌ Errors encountered:');
                foreach ($results['errors'] as $error) {
                    $this->line("  • {$error}");
                }
            } else {
                $this->newLine();
                $this->info('✅ Test completed successfully!');
            }

            return 0;

        } catch (\Exception $e) {
            $this->error('❌ Test failed: ' . $e->getMessage());
            return 1;
        }
    }

    private function createTestData()
    {
        $this->info('🎭 Creating test data with specific actions...');

        // Create a test membership change - user joined
        $committee = Committee::first();
        if ($committee) {
            MsgraphPendingChange::create([
                'model_type' => Committee::class,
                'model_id' => $committee->id,
                'user_id' => 1, // Assuming user ID 1 exists
                'action' => 'user_joined',
                'old_membership_type' => null,
                'new_membership_type' => 'cc', // User joins as CC
                'metadata' => json_encode(['test' => true]),
                'processed' => false
            ]);
            $this->line('  • Created test: user joined committee as CC');
        }

        // Create a test membership type change - from CC to TO
        if ($committee) {
            MsgraphPendingChange::create([
                'model_type' => Committee::class,
                'model_id' => $committee->id,
                'user_id' => 2, // Assuming user ID 2 exists
                'action' => 'user_type_changed',
                'old_membership_type' => 'cc', // Was in CC
                'new_membership_type' => 'to', // Now should be in TO
                'metadata' => json_encode(['test' => true]),
                'processed' => false
            ]);
            $this->line('  • Created test: user changed from CC to TO');
        }

        // Create a test model change - title changed
        $workgroup = WorkGroup::first();
        if ($workgroup) {
            MsgraphModelChange::create([
                'model_type' => WorkGroup::class,
                'model_id' => $workgroup->id,
                'action' => 'title_changed',
                'old_title' => 'Old WorkGroup Title',
                'new_title' => $workgroup->title,
                'language' => 'en',
                'metadata' => json_encode(['test' => true]),
                'processed' => false
            ]);
            $this->line('  • Created test: workgroup title changed');
        }

        // Create a test model change - status changed to published
        if ($workgroup) {
            MsgraphModelChange::create([
                'model_type' => WorkGroup::class,
                'model_id' => $workgroup->id,
                'action' => 'status_changed',
                'old_status' => 'draft',
                'new_status' => 'published',
                'metadata' => json_encode(['test' => true]),
                'processed' => false
            ]);
            $this->line('  • Created test: workgroup status changed to published');
        }

        $this->info('  ✅ Test data created with specific actions');
    }
}
