<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Jobs\ScoreOpportunitiesJob;
use App\Jobs\PushOpportunitiesJob;
use App\Jobs\PushFeaturedAdsJob;

class TestCompleteSystem extends Command
{
    protected $signature = 'ads:test-complete-system';
    protected $description = 'Test the complete ads system with all features';

    public function handle()
    {
        $this->info('🧪 Testing complete ads system...');
        $this->newLine();

        // Step 0: Clean existing test data
        $this->info('🧹 Step 0: Cleaning existing test data...');
        $this->call('ads:clean-test-data');

        // Step 1: Create test data
        $this->info('📝 Step 1: Creating test data...');
        $this->call('ads:create-simple-test');

        // Step 2: Test scoring
        $this->info('🎯 Step 2: Testing scoring system...');
        ScoreOpportunitiesJob::dispatch();

        // Wait for scoring
        sleep(3);

        // Step 3: Test push system
        $this->info('📤 Step 3: Testing push system...');
        $opportunityIds = DB::table('opportunities')
            ->where('status', 'reviewed')
            ->limit(2)
            ->pluck('id')
            ->toArray();

        if (!empty($opportunityIds)) {
            PushOpportunitiesJob::dispatch($opportunityIds, [
                'roles' => ['dealer'],
                'notif_levels' => ['normal']
            ]);
            $this->info("✅ Dispatched push for " . count($opportunityIds) . " opportunities");
        }

        // Step 4: Test featured ads
        $this->info('⭐ Step 4: Testing featured ads...');
        $featuredAdId = DB::table('featured_ads')->value('id');
        if ($featuredAdId) {
            PushFeaturedAdsJob::dispatch($featuredAdId, [
                'roles' => ['dealer'],
                'cities' => ['تهران']
            ]);
            $this->info("✅ Dispatched featured ad push");
        }

        // Step 5: Show results
        $this->info('📊 Step 5: Final results...');
        $this->showResults();

        $this->info('✅ Complete system test completed successfully!');
        return 0;
    }

    private function showResults()
    {
        $this->newLine();
        $this->info('📊 System Test Results:');

        $results = [
            ['Raw Ads', DB::table('ads_raw')->count()],
            ['Total Opportunities', DB::table('opportunities')->count()],
            ['Reviewed Opportunities', DB::table('opportunities')->where('status', 'reviewed')->count()],
            ['Scheduled Opportunities', DB::table('opportunities')->where('status', 'scheduled')->count()],
            ['Sent Opportunities', DB::table('opportunities')->where('status', 'sent')->count()],
            ['Featured Ads', DB::table('featured_ads')->count()],
            ['Scrape Profiles', DB::table('scrape_profiles')->count()],
            ['High Score (≥0.8)', DB::table('opportunities')->where('score', '>=', 0.8)->count()],
            ['Medium Score (0.6-0.8)', DB::table('opportunities')->whereBetween('score', [0.6, 0.8])->count()],
            ['Low Score (<0.6)', DB::table('opportunities')->where('score', '<', 0.6)->count()],
        ];

        $this->table(['Metric', 'Count'], $results);

        // Show sample opportunities
        $this->newLine();
        $this->info('🎯 Sample Opportunities:');
        $sampleOpportunities = DB::table('opportunities')
            ->orderBy('score', 'desc')
            ->limit(5)
            ->get(['code', 'brand', 'model', 'year', 'price', 'score', 'status']);

        $this->table(
            ['Code', 'Brand', 'Model', 'Year', 'Price', 'Score', 'Status'],
            $sampleOpportunities->map(function ($opp) {
                return [
                    $opp->code,
                    $opp->brand,
                    $opp->model,
                    $opp->year,
                    number_format($opp->price) . 'M',
                    number_format($opp->score, 2),
                    $opp->status
                ];
            })->toArray()
        );

        // Show system health
        $this->newLine();
        $this->info('🏥 System Health:');

        $healthIssues = [];

        // Check for stale data
        $staleRaw = DB::table('ads_raw')->where('created_at', '<', now()->subDays(7))->count();
        if ($staleRaw > 0) {
            $healthIssues[] = "⚠️  {$staleRaw} stale raw ads (>7 days)";
        }

        // Check for failed jobs
        $failedJobs = DB::table('failed_jobs')->count();
        if ($failedJobs > 0) {
            $healthIssues[] = "❌ {$failedJobs} failed jobs";
        }

        // Check for opportunities without city
        $noCityOpps = DB::table('opportunities')->whereNull('city_id')->count();
        if ($noCityOpps > 0) {
            $healthIssues[] = "⚠️  {$noCityOpps} opportunities without city";
        }

        if (empty($healthIssues)) {
            $this->info('✅ System is healthy');
        } else {
            foreach ($healthIssues as $issue) {
                $this->warn($issue);
            }
        }
    }
}
