<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\QadSyncController;
use Illuminate\Support\Facades\Log;

class QadSyncCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'qad:sync 
                            {--type=all : Type of sync (stores, menus, all)}
                            {--force : Force sync even if QAD is disabled}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Synchronize master data from QAD system';

    private $qadSyncController;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->qadSyncController = new QadSyncController();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $type = $this->option('type');
        $force = $this->option('force');

        // Check if QAD sync is enabled
        if (!config('services.qad.enabled') && !$force) {
            $this->error('QAD sync is disabled. Use --force to override.');
            return 1;
        }

        $this->info("Starting QAD synchronization for: {$type}");
        $this->info('Time: ' . now()->format('Y-m-d H:i:s'));

        try {
            // Test connection first
            $this->info('Testing QAD connection...');
            $connectionResponse = $this->qadSyncController->testConnection();
            $connectionTest = $connectionResponse->getData(true);
            
            if (!$connectionTest['success']) {
                $this->error('QAD connection failed: ' . $connectionTest['message']);
                return 1;
            }
            
            $this->info('✓ QAD connection successful');

            $result = null;

            switch ($type) {
                case 'stores':
                    $this->info('Syncing stores from QAD...');
                    $response = $this->qadSyncController->syncStores();
                    $result = $response->getData(true);
                    $this->displaySyncResult('Stores', $result);
                    break;

                case 'menus':
                    $this->info('Syncing menus from QAD...');
                    $response = $this->qadSyncController->syncMenus();
                    $result = $response->getData(true);
                    $this->displaySyncResult('Menus', $result);
                    break;

                case 'all':
                    $this->info('Syncing all data from QAD...');
                    $response = $this->qadSyncController->syncAll();
                    $result = $response->getData(true);
                    $this->displayFullSyncResult($result);
                    break;

                default:
                    $this->error("Invalid sync type: {$type}. Use: stores, menus, or all");
                    return 1;
            }

            if ($result && $result['success']) {
                $this->info('✓ QAD synchronization completed successfully');
                Log::info('QAD sync completed via command', [
                    'type' => $type,
                    'result' => $result
                ]);
                return 0;
            } else {
                $this->error('✗ QAD synchronization failed');
                Log::error('QAD sync failed via command', [
                    'type' => $type,
                    'result' => $result
                ]);
                return 1;
            }

        } catch (\Exception $e) {
            $this->error('QAD sync error: ' . $e->getMessage());
            Log::error('QAD sync command error', [
                'type' => $type,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return 1;
        }
    }

    /**
     * Display sync result for individual type
     */
    private function displaySyncResult($type, $result)
    {
        if ($result['success']) {
            $this->info("✓ {$type} sync completed:");
            $this->line("  - Total from QAD: {$result['total_from_qad']}");
            $this->line("  - Inserted: {$result['inserted']}");
            $this->line("  - Updated: {$result['updated']}");
            
            if (!empty($result['errors'])) {
                $this->warn("  - Errors: " . count($result['errors']));
                foreach ($result['errors'] as $error) {
                    $this->line("    • " . ($error['error'] ?? 'Unknown error'));
                }
            }
        } else {
            $this->error("✗ {$type} sync failed: " . $result['message']);
        }
    }

    /**
     * Display sync result for full sync
     */
    private function displayFullSyncResult($result)
    {
        if ($result['success']) {
            $this->info('✓ Full sync completed:');
            
            // Stores result
            $this->line('Stores:');
            $this->line("  - Inserted: {$result['stores']['inserted']}");
            $this->line("  - Updated: {$result['stores']['updated']}");
            if (!empty($result['stores']['errors'])) {
                $this->line("  - Errors: " . count($result['stores']['errors']));
            }
            
            // Menus result
            $this->line('Menus:');
            $this->line("  - Inserted: {$result['menus']['inserted']}");
            $this->line("  - Updated: {$result['menus']['updated']}");
            if (!empty($result['menus']['errors'])) {
                $this->line("  - Errors: " . count($result['menus']['errors']));
            }
            
            // Summary
            $this->line('Summary:');
            $this->line("  - Total inserted: {$result['summary']['total_inserted']}");
            $this->line("  - Total updated: {$result['summary']['total_updated']}");
            $this->line("  - Total errors: {$result['summary']['total_errors']}");
            
        } else {
            $this->error('✗ Full sync failed');
            if (isset($result['stores']) && !$result['stores']['success']) {
                $this->error('  Stores: ' . $result['stores']['message']);
            }
            if (isset($result['menus']) && !$result['menus']['success']) {
                $this->error('  Menus: ' . $result['menus']['message']);
            }
        }
    }
}