<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Transaction;
use App\Models\Category;
use App\Models\CostCenter;
use Illuminate\Support\Facades\DB;

class FixBatchCategorization extends Command
{
    protected $signature = 'fix:batch-categorization 
        {--dry-run : Show what would be changed without making changes}
        {--show : Show current category distribution}
        {--category= : Category ID to remove}
        {--cost-center= : Cost Center ID to remove}
        {--user=3 : User ID}';
        
    protected $description = 'Remove incorrectly applied batch categorization';

    public function handle()
    {
        $dryRun = $this->option('dry-run');
        $show = $this->option('show');
        $userId = $this->option('user');
        
        if ($show) {
            $this->info("Distribuição de categorias para user_id = {$userId}:");
            $distribution = Transaction::where('user_id', $userId)
                ->select('category_id', 'cost_center_id', DB::raw('count(*) as total'))
                ->groupBy('category_id', 'cost_center_id')
                ->orderByDesc('total')
                ->limit(20)
                ->get();
                
            $this->table(
                ['Category ID', 'Category Name', 'Cost Center ID', 'Cost Center Name', 'Total'],
                $distribution->map(function($row) {
                    $cat = $row->category_id ? Category::find($row->category_id) : null;
                    $cc = $row->cost_center_id ? CostCenter::find($row->cost_center_id) : null;
                    return [
                        $row->category_id ?? 'NULL',
                        $cat?->name ?? '-',
                        $row->cost_center_id ?? 'NULL',
                        $cc?->name ?? '-',
                        $row->total
                    ];
                })
            );
            return 0;
        }
        
        $categoryId = $this->option('category');
        $costCenterId = $this->option('cost-center');
        
        if (!$categoryId && !$costCenterId) {
            $this->error('Especifique --category e/ou --cost-center para remover');
            $this->info('Use --show para ver a distribuição atual');
            return 1;
        }
        
        // Construir query
        $query = Transaction::where('user_id', $userId);
        
        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }
        if ($costCenterId) {
            $query->where('cost_center_id', $costCenterId);
        }
        
        $affected = $query->count();
        
        $category = $categoryId ? Category::find($categoryId) : null;
        $costCenter = $costCenterId ? CostCenter::find($costCenterId) : null;
        
        $this->info("Categoria: " . ($categoryId ?? 'N/A') . " - " . ($category?->name ?? 'NOT FOUND'));
        $this->info("Centro de Custo: " . ($costCenterId ?? 'N/A') . " - " . ($costCenter?->name ?? 'NOT FOUND'));
        $this->info("Transações afetadas: {$affected}");
        
        if ($dryRun) {
            $this->warn('DRY RUN - Nenhuma alteração feita');
            return 0;
        }
        
        if ($affected == 0) {
            $this->info('Nenhuma transação para atualizar');
            return 0;
        }
        
        // Remover categorização
        $updateData = [];
        if ($categoryId) {
            $updateData['category_id'] = null;
        }
        if ($costCenterId) {
            $updateData['cost_center_id'] = null;
        }
        
        $updated = $query->update($updateData);
            
        $this->info("✅ {$updated} transações atualizadas");
        
        return 0;
    }
}
