<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Structure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * @deprecated Esta seeder foi consolidada em ProjetosProgramasMigrationSeeder.
 * Use: php artisan db:seed --class=ProjetosProgramasMigrationSeeder
 *
 * Esta seeder ainda existe para referência, mas não deve ser executada diretamente.
 * A seeder consolidada inclui esta funcionalidade e muito mais.
 */
class LegacyProjetosOrgaosSeeder extends Seeder
{
    private array $orgaoMap = [];

    public function run(): void
    {
        $this->command->info('Iniciando migração de órgãos...');

        $csvPath = base_path('Orgaos.csv');

        if (!file_exists($csvPath)) {
            $this->command->error("Arquivo não encontrado: {$csvPath}");
            return;
        }

        $handle = fopen($csvPath, 'r');
        if (!$handle) {
            $this->command->error("Não foi possível abrir o arquivo: {$csvPath}");
            return;
        }

        // Read header
        $header = fgetcsv($handle);
        if (!$header) {
            $this->command->error("Arquivo CSV vazio ou inválido");
            fclose($handle);
            return;
        }

        // Remove BOM if present
        $header[0] = preg_replace('/^\x{FEFF}/u', '', $header[0]);

        $this->command->info("Colunas encontradas: " . implode(', ', $header));

        $created = 0;
        $updated = 0;
        $skipped = 0;

        while (($row = fgetcsv($handle)) !== false) {
            if (count($row) < count($header)) {
                continue;
            }

            $data = array_combine($header, $row);

            $idOrg = trim($data['id_org'] ?? '');
            $sigla = trim($data['org_sigla'] ?? '');
            $nome = trim($data['org_nome'] ?? '');

            if (empty($idOrg) || empty($sigla) || empty($nome)) {
                $skipped++;
                continue;
            }

            // Try to find existing structure by abbreviation
            $structure = Structure::where('abbreviation', $sigla)->first();

            if (!$structure) {
                // Create new structure
                $structure = Structure::create([
                    'id' => Str::uuid(),
                    'structure_id' => null,
                    'type' => 'SECRETARIA',
                    'name' => $nome,
                    'abbreviation' => $sigla,
                    'slug' => Str::slug($sigla),
                    'address' => '',
                    'phoneNumber' => '',
                    'email1' => 'contato@angra.rj.gov.br',
                    'manager' => '',
                    'status' => 'ATIVADO',
                    'order' => (int) ($data['org_numero'] ?? 0),
                ]);
                $created++;
                $this->command->info("Criado: {$sigla} - {$nome}");
            } else {
                $updated++;
            }

            // Store mapping
            $this->orgaoMap[$idOrg] = $structure->id;
        }

        fclose($handle);

        // Store mapping in cache for use by other seeders
        cache()->put('legacy_orgao_map', $this->orgaoMap, now()->addHours(24));

        $this->command->info("Migração de órgãos concluída!");
        $this->command->info("Criados: {$created}");
        $this->command->info("Existentes: {$updated}");
        $this->command->info("Ignorados: {$skipped}");
    }

    public function getOrgaoMap(): array
    {
        return $this->orgaoMap;
    }
}
