<?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\PushSchedulerJob;

class StartAdsSystem extends Command
{
    protected $signature = 'ads:start {--test : Use test data}';
    protected $description = 'Start the complete ads system';

    public function handle()
    {
        $this->info('🚀 Starting HajiBot Ads System...');
        $this->newLine();

        // Check system requirements
        if (!$this->checkRequirements()) {
            return 1;
        }

        // Create test data if requested
        if ($this->option('test')) {
            $this->info('📝 Creating test data...');
            $this->call('ads:create-test-data');
            $this->newLine();
        }

        // Start data collection
        $this->info('📥 Starting data collection...');
        if ($this->option('test')) {
            BamaPullLatestJob::dispatch(1, true);
        } else {
            BamaPullLatestJob::dispatch(1, false);
        }

        // Wait for data collection
        $this->info('⏳ Waiting for data collection...');
        sleep(5);

        // Start scoring
        $this->info('🎯 Starting scoring system...');
        ScoreOpportunitiesJob::dispatch();

        // Wait for scoring
        sleep(3);

        // Start push scheduler
        $this->info('📤 Starting push scheduler...');
        PushSchedulerJob::dispatch();

        // Show initial status
        $this->newLine();
        $this->info('📊 Initial System Status:');
        $this->call('ads:status');

        $this->newLine();
        $this->info('✅ Ads system started successfully!');
        $this->info('💡 Use "php artisan ads:status" to check system status');
        $this->info('💡 Use "php artisan ads:pipeline" to run full pipeline');
        $this->info('💡 Use "php artisan queue:work" to process jobs');

        return 0;
    }

    private function checkRequirements(): bool
    {
        $this->info('🔍 Checking system requirements...');

        $issues = [];

        // Check database connection
        try {
            DB::connection()->getPdo();
        } catch (\Throwable $e) {
            $issues[] = '❌ Database connection failed';
        }

        // Check required tables
        $requiredTables = ['ads_raw', 'opportunities', 'featured_ads', 'scrape_profiles', 'cities'];
        foreach ($requiredTables as $table) {
            if (!DB::getSchemaBuilder()->hasTable($table)) {
                $issues[] = "❌ Table '{$table}' does not exist";
            }
        }

        // Check cities data
        $citiesCount = DB::table('cities')->count();
        if ($citiesCount === 0) {
            $issues[] = '❌ No cities found in database';
        }

        // Check environment variables
        if (empty(env('MAJIDAPI_BASE_URL'))) {
            $issues[] = '❌ MAJIDAPI_BASE_URL not set';
        }

        if (empty($issues)) {
            $this->info('✅ All requirements met');
            return true;
        }

        $this->error('❌ System requirements not met:');
        foreach ($issues as $issue) {
            $this->error($issue);
        }

        return false;
    }
}
