<?php

namespace App\Console\Commands;

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

class TestCompleteAdsSystem extends Command
{
    protected $signature = 'ads:test-complete {--fixtures : Use fixture data}';
    protected $description = 'Test the complete ads system end-to-end';

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

        // Step 1: Clean up existing data
        $this->info('🧹 Cleaning up existing test data...');
        DB::table('ads_raw')->where('source', 'like', 'test%')->delete();
        DB::table('opportunities')->where('code', 'like', 'test%')->delete();
        DB::table('featured_ads')->where('title', 'like', '%تست%')->delete();

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

        // Step 3: Test data collection
        $this->info('📥 Testing data collection...');
        if ($this->option('fixtures')) {
            BamaPullLatestJob::dispatch(1, true);
        } else {
            BamaPullLatestJob::dispatch(1, false);
        }

        // Wait for collection
        sleep(3);

        $rawCount = DB::table('ads_raw')->count();
        $this->info("✅ Collected {$rawCount} raw ads");

        if ($rawCount === 0) {
            $this->error('❌ No raw data collected');
            return 1;
        }

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

        // Wait for scoring
        sleep(3);

        $opportunitiesCount = DB::table('opportunities')->count();
        $reviewedCount = DB::table('opportunities')->where('status', 'reviewed')->count();
        $this->info("✅ Created {$opportunitiesCount} opportunities ({$reviewedCount} reviewed)");

        if ($opportunitiesCount === 0) {
            $this->error('❌ No opportunities created');
            return 1;
        }

        // Step 5: Test push system
        $this->info('📤 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 6: Test featured ads
        $this->info('⭐ 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 7: Test admin panel
        $this->info('🔧 Testing admin panel...');
        $this->testAdminPanel();

        // Step 8: Show final results
        $this->showFinalResults();

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

    private function testAdminPanel()
    {
        // Test opportunities API
        $response = $this->call('GET', '/api/admin/opportunities');
        if ($response->getStatusCode() === 200) {
            $this->info('✅ Opportunities API working');
        } else {
            $this->warn('⚠️  Opportunities API not accessible');
        }

        // Test featured ads API
        $response = $this->call('GET', '/api/admin/featured-ads');
        if ($response->getStatusCode() === 200) {
            $this->info('✅ Featured ads API working');
        } else {
            $this->warn('⚠️  Featured ads API not accessible');
        }
    }

    private function showFinalResults()
    {
        $this->newLine();
        $this->info('📊 Final 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()],
        ];

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

        // Show sample opportunities
        $this->newLine();
        $this->info('🎯 Sample Opportunities:');
        $sampleOpportunities = DB::table('opportunities')
            ->orderBy('score', 'desc')
            ->limit(3)
            ->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()
        );
    }
}
