<?php

use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\PasswordResetController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\BrandingController;
use App\Http\Controllers\Instalador\InstaladorController;
use App\Http\Controllers\Master;
use App\Http\Controllers\Painel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

// As demais rotas do instalador vivem em routes/instalador.php, com pilha
// própria. Esta fica aqui porque precisa abrir depois da trava.
Route::get('/instalar/concluido', [InstaladorController::class, 'concluido'])->name('instalador.concluido');

Route::view('/', 'landing')->name('home');

// Logo e favicon: arquivos privados servidos pela aplicação, sem storage:link.
Route::get('/marca/{tipo}', BrandingController::class)
    ->whereIn('tipo', ['logo', 'logo-claro', 'favicon'])
    ->name('marca');

/*
|--------------------------------------------------------------------------
| Autenticação
|--------------------------------------------------------------------------
*/

Route::middleware('guest')->group(function () {
    Route::get('/entrar', [LoginController::class, 'create'])->name('login');
    Route::post('/entrar', [LoginController::class, 'store'])->middleware('throttle:10,1');

    Route::get('/cadastrar', [RegisterController::class, 'create'])->name('register');
    Route::post('/cadastrar', [RegisterController::class, 'store'])->middleware('throttle:6,1');

    Route::get('/recuperar-senha', [PasswordResetController::class, 'request'])->name('password.request');
    Route::post('/recuperar-senha', [PasswordResetController::class, 'email'])
        ->middleware('throttle:6,1')->name('password.email');
    Route::get('/redefinir-senha/{token}', [PasswordResetController::class, 'reset'])->name('password.reset');
    Route::post('/redefinir-senha', [PasswordResetController::class, 'update'])->name('password.update');
});

Route::post('/sair', [LoginController::class, 'destroy'])->middleware('auth')->name('logout');

/*
|--------------------------------------------------------------------------
| Painel da empresa
|--------------------------------------------------------------------------
*/

Route::middleware(['auth', 'empresa.ativa'])->prefix('painel')->name('painel.')->group(function () {
    Route::get('/', Painel\DashboardController::class)->name('dashboard');

    Route::view('/consulta', 'painel.consulta')->name('consulta');

    Route::get('/notas', [Painel\NotaFiscalController::class, 'index'])->name('notas');
    Route::get('/download-lote', Painel\DownloadLoteController::class)->name('download.lote');
    Route::get('/notas/{nota}', [Painel\NotaFiscalController::class, 'show'])->name('notas.show');
    Route::get('/notas/{nota}/xml', [Painel\NotaFiscalController::class, 'download'])->name('notas.download');
    Route::get('/notas/{nota}/danfe', [Painel\NotaFiscalController::class, 'danfe'])->name('notas.danfe');
    Route::post('/notas/{nota}/manifestar', [Painel\NotaFiscalController::class, 'manifestar'])->name('notas.manifestar');

    Route::get('/certificado', [Painel\CertificadoController::class, 'edit'])->name('certificado');
    Route::post('/certificado', [Painel\CertificadoController::class, 'update'])->name('certificado.update');
    Route::delete('/certificado', [Painel\CertificadoController::class, 'destroy'])->name('certificado.destroy');

    Route::get('/monitor', [Painel\MonitorController::class, 'edit'])->name('monitor');
    Route::put('/monitor', [Painel\MonitorController::class, 'update'])->name('monitor.update');
    Route::post('/monitor/sincronizar', [Painel\MonitorController::class, 'sincronizar'])
        ->middleware('throttle:10,60')->name('monitor.sincronizar');
    Route::post('/monitor/enfileirar', [Painel\MonitorController::class, 'enfileirar'])->name('monitor.enfileirar');

    Route::get('/usuarios', [Painel\UsuarioController::class, 'index'])->name('usuarios');
    Route::post('/usuarios', [Painel\UsuarioController::class, 'store'])->name('usuarios.store');
    Route::put('/usuarios/{usuario}', [Painel\UsuarioController::class, 'update'])->name('usuarios.update');
    Route::delete('/usuarios/{usuario}', [Painel\UsuarioController::class, 'destroy'])->name('usuarios.destroy');
});

// Encerrar a personificação precisa continuar acessível depois da troca de identidade,
// por isso fica fora do grupo protegido pelo middleware "master".
Route::post('/master/voltar', [Master\ImpersonateController::class, 'stop'])
    ->middleware('auth')->name('master.impersonate.stop');

/*
|--------------------------------------------------------------------------
| Painel master
|--------------------------------------------------------------------------
*/

Route::middleware(['auth', 'master'])->prefix('master')->name('master.')->group(function () {
    Route::get('/', Master\DashboardController::class)->name('dashboard');

    Route::get('/empresas', [Master\CompanyController::class, 'index'])->name('empresas.index');
    Route::get('/empresas/nova', [Master\CompanyController::class, 'create'])->name('empresas.create');
    Route::post('/empresas', [Master\CompanyController::class, 'store'])->name('empresas.store');
    Route::get('/empresas/{empresa}', [Master\CompanyController::class, 'show'])->name('empresas.show');
    Route::put('/empresas/{empresa}', [Master\CompanyController::class, 'update'])->name('empresas.update');
    Route::delete('/empresas/{empresa}', [Master\CompanyController::class, 'destroy'])->name('empresas.destroy');
    Route::post('/empresas/{empresa}/sincronizar', [Master\CompanyController::class, 'sincronizar'])->name('empresas.sincronizar');
    Route::post('/empresas/{empresa}/reiniciar-nsu', [Master\CompanyController::class, 'reiniciarNsu'])->name('empresas.nsu');
    Route::post('/empresas/{empresa}/acessar', [Master\ImpersonateController::class, 'start'])->name('empresas.impersonate');

    Route::get('/notas', [Master\NotaGlobalController::class, 'index'])->name('notas');
    Route::get('/logs', [Master\NotaGlobalController::class, 'logs'])->name('logs');

    // O master enxerga qualquer nota (o CompanyScope não se aplica a ele), mas
    // precisa de rotas próprias: as do painel exigem vínculo com empresa.
    Route::view('/consulta', 'master.consulta')->name('consulta');
    Route::get('/notas/{nota}', [Painel\NotaFiscalController::class, 'show'])->name('notas.show');
    Route::get('/notas/{nota}/xml', [Painel\NotaFiscalController::class, 'download'])->name('notas.download');
    Route::get('/notas/{nota}/danfe', [Painel\NotaFiscalController::class, 'danfe'])->name('notas.danfe');

    Route::get('/certificados', [Master\CertificadoGlobalController::class, 'index'])->name('certificados');
    Route::post('/certificados/{empresa}', [Master\CertificadoGlobalController::class, 'store'])->name('certificados.store');
    Route::delete('/certificados/{empresa}', [Master\CertificadoGlobalController::class, 'destroy'])->name('certificados.destroy');

    Route::get('/usuarios', [Master\UsuarioGlobalController::class, 'index'])->name('usuarios');
    Route::post('/usuarios', [Master\UsuarioGlobalController::class, 'store'])->name('usuarios.store');
    Route::put('/usuarios/{usuario}', [Master\UsuarioGlobalController::class, 'update'])->name('usuarios.update');
    Route::delete('/usuarios/{usuario}', [Master\UsuarioGlobalController::class, 'destroy'])->name('usuarios.destroy');

    Route::get('/configuracoes', [Master\ConfiguracaoController::class, 'edit'])->name('configuracoes');
    Route::put('/configuracoes', [Master\ConfiguracaoController::class, 'update'])->name('configuracoes.update');
    Route::delete('/configuracoes/imagem', [Master\ConfiguracaoController::class, 'removerImagem'])->name('configuracoes.imagem');
    Route::post('/configuracoes/restaurar', [Master\ConfiguracaoController::class, 'restaurar'])->name('configuracoes.restaurar');
});

Route::get('/painel-inicial', fn () => Auth::user()->isMaster()
    ? redirect()->route('master.dashboard')
    : redirect()->route('painel.dashboard'))
    ->middleware('auth')->name('painel.inicial');
