<?php

namespace App\Console\Commands;

use App\Services\TrelloService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class TestTrello extends Command
{
    protected $signature = 'trello:test';
    protected $description = 'Test Trello integration with dummy data';

    public function handle()
    {
        $this->info('Testing Trello integration...');
        $this->newLine();

        // Check environment variables
        $this->info('Checking environment variables:');
        $apiKey = config('trello.api_key');
        $apiToken = config('trello.api_token');
        $boardId = config('trello.board_id');

        $this->line('  API Key: ' . ($apiKey ? '✓ Set (' . substr($apiKey, 0, 8) . '...)' : '✗ Empty'));
        $this->line('  API Token: ' . ($apiToken ? '✓ Set (' . substr($apiToken, 0, 8) . '...)' : '✗ Empty'));
        $this->line('  Board ID: ' . ($boardId ? '✓ Set (' . $boardId . ')' : '✗ Empty'));
        $this->newLine();

        // Check list IDs
        $this->info('Checking list IDs (standard):');
        $lists = config('trello.lists.standard');
        foreach ($lists as $key => $id) {
            $this->line('  ' . str_replace('_', ' ', ucfirst($key)) . ': ' . ($id ? '✓ ' . $id : '✗ Empty'));
        }
        $this->newLine();

        // Try to create a test card
        $this->info('Attempting to create a test card...');
        try {
            $service = new TrelloService();
            
            $cardId = $service->createCard(
                'test-uuid-12345',
                'TEST-20260102-00000000',
                'standard'
            );

            if ($cardId) {
                $this->info("✓ Test card created successfully!");
                $this->line("  Card ID: {$cardId}");
                $this->newLine();

                // Try to move the card
                $this->info('Attempting to move test card to "Packing"...');
                $moved = $service->moveCard($cardId, 'Packing');
                if ($moved) {
                    $this->info('✓ Card moved successfully!');
                } else {
                    $this->warn('✗ Failed to move card (check list names)');
                }
                $this->newLine();

                $this->info('Testing complete! Trello is configured correctly.');
            } else {
                $this->warn('✗ Failed to create test card');
                $this->line('Check logs for more details: storage/logs/laravel.log');
            }
        } catch (\Exception $e) {
            $this->error('✗ Exception: ' . $e->getMessage());
            Log::error('Trello test command failed', ['error' => $e->getMessage()]);
        }
    }
}
