<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\PerizinanApiService;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class SyncPerizinanData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'perizinan:sync {kategori?} {--fastest : Include fastest permohonan data sync} {--terakhir-terbit : Include terakhir terbit data sync} {--all : Include all data types (fastest + terakhir terbit)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync perizinan data from API to database (status, fastest permohonan, and terakhir terbit)';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $startTime = Carbon::now();
        $kategori = $this->argument('kategori');
        $includeFastest = $this->option('fastest');
        $includeTerakhirTerbit = $this->option('terakhir-terbit');
        $includeAll = $this->option('all');

        // If --all is specified, include both fastest and terakhir terbit
        if ($includeAll) {
            $includeFastest = true;
            $includeTerakhirTerbit = true;
        }

        Log::info('Starting perizinan data sync', [
            'kategori' => $kategori,
            'include_fastest' => $includeFastest,
            'include_terakhir_terbit' => $includeTerakhirTerbit,
            'start_time' => $startTime->format('Y-m-d H:i:s')
        ]);

        $this->info('🚀 Starting perizinan data synchronization...');
        if ($includeFastest) {
            $this->info('⚡ Including fastest permohonan data sync');
        }
        if ($includeTerakhirTerbit) {
            $this->info('📋 Including terakhir terbit data sync');
        }

        $service = new PerizinanApiService();

        try {
            if ($kategori) {
                // Sync specific category
                $this->info("📥 Syncing status data for kategori: {$kategori}");
                $statusResult = $service->syncToDatabase($kategori);

                if ($statusResult) {
                    $this->info("✅ Successfully synced status data for kategori: {$kategori}");
                } else {
                    $this->error("❌ Failed to sync status data for kategori: {$kategori}");
                }

                // Sync fastest data if requested
                if ($includeFastest) {
                    $this->info("⚡ Syncing fastest permohonan data for kategori: {$kategori}");
                    $fastestResult = $service->syncFastestDataToDatabase($kategori, 5);

                    if ($fastestResult) {
                        $this->info("✅ Successfully synced fastest data for kategori: {$kategori}");
                    } else {
                        $this->error("❌ Failed to sync fastest data for kategori: {$kategori}");
                    }
                }

                // Sync terakhir terbit data if requested
                if ($includeTerakhirTerbit) {
                    $this->info("📋 Syncing terakhir terbit data for kategori: {$kategori}");
                    $terakhirTerbitResult = $service->syncTerakhirTerbitToDatabase($kategori, 5);

                    if ($terakhirTerbitResult) {
                        $this->info("✅ Successfully synced terakhir terbit data for kategori: {$kategori}");
                    } else {
                        $this->error("❌ Failed to sync terakhir terbit data for kategori: {$kategori}");
                    }
                }
            } else {
                // Sync all categories
                $this->info("📥 Syncing data for all categories...");
                $results = $service->syncAllCategories($includeFastest, $includeTerakhirTerbit);

                foreach ($results as $cat => $result) {
                    if (isset($result['status']) && $result['status']) {
                        $this->info("✅ Successfully synced status data for kategori: {$cat}");
                    } else {
                        $this->error("❌ Failed to sync status data for kategori: {$cat}");
                    }

                    if ($includeFastest) {
                        if (isset($result['fastest']) && $result['fastest']) {
                            $this->info("✅ Successfully synced fastest data for kategori: {$cat}");
                        } else {
                            $this->error("❌ Failed to sync fastest data for kategori: {$cat}");
                        }
                    }

                    if ($includeTerakhirTerbit) {
                        if (isset($result['terakhir_terbit']) && $result['terakhir_terbit']) {
                            $this->info("✅ Successfully synced terakhir terbit data for kategori: {$cat}");
                        } else {
                            $this->error("❌ Failed to sync terakhir terbit data for kategori: {$cat}");
                        }
                    }
                }
            }

            $endTime = Carbon::now();
            $duration = $endTime->diffInSeconds($startTime, true);

            $this->info("🎉 Data synchronization completed in {$duration} seconds");

            Log::info('Perizinan data sync completed', [
                'kategori' => $kategori ?: 'all',
                'include_fastest' => $includeFastest,
                'include_terakhir_terbit' => $includeTerakhirTerbit,
                'duration_seconds' => $duration,
                'end_time' => $endTime->format('Y-m-d H:i:s')
            ]);

        } catch (\Exception $e) {
            $this->error("💥 An error occurred: " . $e->getMessage());

            Log::error('Perizinan data sync failed', [
                'kategori' => $kategori ?: 'all',
                'include_fastest' => $includeFastest,
                'include_terakhir_terbit' => $includeTerakhirTerbit,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return 1;
        }

        return 0;
    }
}
