<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class VerificarCarregamentoUserIsActive extends Command
{
    protected $signature = 'check:user-is-active-loading';
    protected $description = 'Verifica se todos os carregamentos do relacionamento user incluem is_active';

    public function handle()
    {
        $this->info("Verificando carregamentos do relacionamento 'user' sem 'is_active'...\n");
        
        $controllersPath = app_path('Http/Controllers');
        $files = File::allFiles($controllersPath);
        
        $problemas = [];
        $totalVerificados = 0;
        
        foreach ($files as $file) {
            $content = File::get($file->getPathname());
            $relativePath = str_replace(base_path() . DIRECTORY_SEPARATOR, '', $file->getPathname());
            
            // Procurar por padrões de carregamento do relacionamento user
            // Padrões: ->with('user:...), ->with(['user:...]), ->with(['aluno.user:...])
            $patterns = [
                "/->with\(['\"]user:id,([^'\"]*)['\"]\)/",
                "/->with\(\[['\"]user:id,([^'\"]*)['\"]\]\)/",
                "/'user:id,([^']*)'/",
                "/\"user:id,([^\"]*)\"/",
                "/'aluno\.user:id,([^']*)'/",
                "/\"aluno\.user:id,([^\"]*)\"/",
            ];
            
            foreach ($patterns as $pattern) {
                if (preg_match_all($pattern, $content, $matches)) {
                    foreach ($matches[1] as $match) {
                        $totalVerificados++;
                        $campos = explode(',', $match);
                        
                        // Verificar se is_active está presente
                        if (!in_array('is_active', $campos)) {
                            $problemas[] = [
                                'arquivo' => $relativePath,
                                'linha' => $this->getLineNumber($content, $match),
                                'campos' => $match,
                            ];
                        }
                    }
                }
            }
        }
        
        if (empty($problemas)) {
            $this->info("✓ Todos os carregamentos do relacionamento 'user' incluem 'is_active'!");
            $this->info("  Total de carregamentos verificados: {$totalVerificados}");
            return 0;
        }
        
        $this->error("✗ Encontrados " . count($problemas) . " problemas:");
        foreach ($problemas as $problema) {
            $this->line("  - {$problema['arquivo']}:{$problema['linha']}");
            $this->line("    Campos: {$problema['campos']}");
            $this->line("    → Adicione 'is_active' aos campos selecionados");
        }
        
        return 1;
    }
    
    private function getLineNumber($content, $search)
    {
        $lines = explode("\n", $content);
        foreach ($lines as $num => $line) {
            if (strpos($line, $search) !== false) {
                return $num + 1;
            }
        }
        return 0;
    }
}
