<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\PerizinanStatus;
use App\Services\PerizinanApiService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Artisan;
use Carbon\Carbon;

class TestProductionSetup extends Command
{
    protected $signature = 'perizinan:test-production';
    protected $description = 'Test production setup readiness';

    public function handle()
    {
        $this->info('🔍 Testing Production Setup Readiness...');
        $this->newLine();

        $allPassed = true;

        // Test 1: Database Connection
        $this->info('1. Testing Database Connection...');
        try {
            DB::connection()->getPdo();
            $this->line('   ✅ Database connection successful');
        } catch (\Exception $e) {
            $this->error('   ❌ Database connection failed: ' . $e->getMessage());
            $allPassed = false;
        }

        // Test 2: Database Table
        $this->info('2. Testing Database Table...');
        try {
            $count = PerizinanStatus::count();
            $this->line("   ✅ PerizinanStatus table exists with {$count} records");
        } catch (\Exception $e) {
            $this->error('   ❌ Database table issue: ' . $e->getMessage());
            $allPassed = false;
        }

        // Test 3: API Configuration
        $this->info('3. Testing API Configuration...');
        $bearerToken = config('services.perizinan.bearer_token');
        $apiKey = config('services.perizinan.api_key');

        if ($bearerToken && $bearerToken !== 'your_actual_bearer_token') {
            $this->line('   ✅ Bearer token configured');
        } else {
            $this->error('   ❌ Bearer token not configured properly');
            $allPassed = false;
        }

        if ($apiKey && $apiKey !== 'your_actual_api_key') {
            $this->line('   ✅ API key configured');
        } else {
            $this->error('   ❌ API key not configured properly');
            $allPassed = false;
        }

        // Test 4: API Connection
        $this->info('4. Testing API Connection...');
        try {
            $service = new PerizinanApiService();
            $response = $service->fetchSummaryByStatus('pertek');

            if ($response && ($response['success'] ?? false)) {
                $this->line('   ✅ API connection successful');
                $dataCount = count($response['data'] ?? []);
                $this->line("   📊 Retrieved {$dataCount} data items");
            } else {
                $this->error('   ❌ API response invalid');
                $allPassed = false;
            }
        } catch (\Exception $e) {
            $this->error('   ❌ API connection failed: ' . $e->getMessage());
            $allPassed = false;
        }

        // Test 5: Storage Permissions
        $this->info('5. Testing Storage Permissions...');
        $logPath = storage_path('logs/test-' . time() . '.log');
        try {
            file_put_contents($logPath, 'test');
            unlink($logPath);
            $this->line('   ✅ Storage directory writable');
        } catch (\Exception $e) {
            $this->error('   ❌ Storage permission issue: ' . $e->getMessage());
            $allPassed = false;
        }

        // Test 6: Schedule Configuration
        $this->info('6. Testing Schedule Configuration...');
        try {
            Artisan::call('schedule:list');
            $this->line('   ✅ Laravel scheduler configured');
            $this->line('   📅 Run "php artisan schedule:list" to see scheduled commands');
        } catch (\Exception $e) {
            $this->error('   ❌ Scheduler issue: ' . $e->getMessage());
            $allPassed = false;
        }

        $this->newLine();

        if ($allPassed) {
            $this->info('🎉 All tests passed! Production setup is ready.');
            $this->newLine();
            $this->info('Next steps:');
            $this->line('1. Deploy to production server');
            $this->line('2. Run: chmod +x *.sh');
            $this->line('3. Run: ./deploy-production.sh');
            $this->line('4. Setup cron job as per PRODUCTION_DEPLOY.md');
        } else {
            $this->error('❌ Some tests failed. Please fix the issues above.');
            return 1;
        }

        return 0;
    }
}
