<?php

use App\Http\Controllers\Admin\AccrualEmailConfirmationController;
use App\Http\Controllers\Admin\AdminDashboardController;
use App\Http\Controllers\Admin\AdminDebugController;
use App\Http\Controllers\Admin\AdminImpersonationController;
use App\Http\Controllers\Admin\AdminKycDocumentDownloadController;
use App\Http\Controllers\Admin\AdminKycReviewController;
use App\Http\Controllers\Admin\AdminNotificationSettingsController;
use App\Http\Controllers\Admin\AdminUserDirectoryController;
use App\Http\Controllers\Admin\ForexImportStagingController;
use App\Http\Controllers\Admin\InvestmentBalancesController;
use App\Http\Controllers\Admin\InvestmentManageController;
use App\Http\Controllers\Admin\InvestmentSettingsController;
use App\Http\Controllers\Admin\LegalDocumentController as AdminLegalDocumentController;
use App\Http\Controllers\Admin\PlatformMonthlyAccrualController;
use App\Http\Controllers\Admin\WithdrawalHistoryController;
use App\Http\Controllers\Admin\WithdrawalRequestManageController;
use App\Http\Controllers\BalancesWithdrawalRequestController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\EmailConfirmationController;
use App\Http\Controllers\InvestmentController;
use App\Http\Controllers\InvestmentTransactionsController;
use App\Http\Controllers\InvestorBalancesController;
use App\Http\Controllers\InvestorMovementsController;
use App\Http\Controllers\KycVerificationController;
use App\Http\Controllers\LegalDocumentController;
use App\Http\Controllers\MyInvestmentsController;
use App\Http\Controllers\ReferralController;
use App\Http\Controllers\UserWalletController;
use App\Support\MaintenanceMode;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use Inertia\Response;

Route::get('/', static function (): RedirectResponse {
    if (MaintenanceMode::enabled() && ! MaintenanceMode::allowsUser(Auth::user())) {
        return redirect()->route('maintenance');
    }

    return Auth::check()
        ? redirect()->route('dashboard')
        : redirect()->route('login');
})->name('home');

Route::get('mantenimiento', static function (): Response {
    return Inertia::render('maintenance');
})->name('maintenance');

Route::get('documentos-legales/{legalDocument:key}', [LegalDocumentController::class, 'show'])
    ->name('legal-documents.show');

Route::middleware('throttle:30,1')->group(function (): void {
    Route::get('confirmaciones/correo/inversion/{token}', [EmailConfirmationController::class, 'investment'])
        ->name('confirm.email.investment');
    Route::get('confirmaciones/correo/retiro/{token}', [EmailConfirmationController::class, 'withdrawal'])
        ->name('confirm.email.withdrawal');
});

Route::middleware(['auth', 'verified'])->group(function (): void {
    Route::get('verificacion-kyc', [KycVerificationController::class, 'show'])->name('kyc.show');
    Route::post('verificacion-kyc', [KycVerificationController::class, 'store'])
        ->middleware('throttle:15,1')
        ->name('kyc.store');

    Route::get('dashboard', DashboardController::class)->name('dashboard');
    Route::get('referidos', [ReferralController::class, 'index'])->name('referrals.index');
    Route::get('mis-inversiones', [MyInvestmentsController::class, 'index'])
        ->name('investments.mine');
    Route::get('mis-inversiones/{investment}/movimientos', [InvestmentTransactionsController::class, 'index'])
        ->name('investments.transactions');
    Route::get('invertir', [InvestmentController::class, 'index'])->name('investments.index');
    Route::post('invertir', [InvestmentController::class, 'store'])
        ->middleware('investor.kyc:invest')
        ->name('investments.store');

    Route::get('balances', [InvestorBalancesController::class, 'index'])
        ->name('balances.index');
    Route::post('balances/solicitud-retiro', [BalancesWithdrawalRequestController::class, 'store'])
        ->middleware('investor.kyc:withdraw')
        ->name('balances.withdrawals.store');
    Route::get('balances/movimientos', [InvestorMovementsController::class, 'index'])
        ->name('balances.movements');
    Route::get('balances/billeteras', [UserWalletController::class, 'index'])
        ->name('balances.wallets');
    Route::post('balances/billeteras', [UserWalletController::class, 'store'])
        ->middleware('investor.kyc:wallet')
        ->name('balances.wallets.store');
    Route::put('balances/billeteras/{user_wallet}', [UserWalletController::class, 'update'])
        ->name('balances.wallets.update');
    Route::delete('balances/billeteras/{user_wallet}', [UserWalletController::class, 'destroy'])
        ->name('balances.wallets.destroy');

    Route::post('impersonacion/finalizar', [AdminImpersonationController::class, 'stop'])
        ->name('impersonation.stop');
});

Route::middleware(['auth', 'verified', 'investor.kyc', 'admin'])->prefix('admin')->group(function (): void {
    Route::get('/', [AdminDashboardController::class, 'index'])->name('admin.home');

    Route::get('usuarios', [AdminUserDirectoryController::class, 'index'])
        ->name('admin.users.index');
    Route::get('usuarios/referidor-sugerencias', [AdminUserDirectoryController::class, 'referrerSuggestions'])
        ->name('admin.users.referrer-suggestions');
    Route::get('usuarios/{user}/editar', [AdminUserDirectoryController::class, 'edit'])
        ->name('admin.users.edit');
    Route::post('usuarios/{user}/impersonar', [AdminImpersonationController::class, 'start'])
        ->name('admin.users.impersonate.start');
    Route::post('usuarios/{user}/referidos-manuales', [AdminUserDirectoryController::class, 'attachManualDirectReferral'])
        ->name('admin.users.manual-direct-referrals.attach');
    Route::delete('usuarios/{user}/referidos-manuales/{referred}', [AdminUserDirectoryController::class, 'detachManualDirectReferral'])
        ->name('admin.users.manual-direct-referrals.detach');
    Route::patch('usuarios/{user}', [AdminUserDirectoryController::class, 'update'])
        ->name('admin.users.update');
    Route::post('usuarios/{user}/balance-manual', [AdminUserDirectoryController::class, 'addManualBalance'])
        ->name('admin.users.manual-balance');
    Route::post('usuarios/{user}/consolidar-balance', [AdminUserDirectoryController::class, 'consolidateBalance'])
        ->name('admin.users.consolidate-balance');
    Route::get('usuarios/{user}/consolidar-balance/preview', [AdminUserDirectoryController::class, 'consolidateBalancePreview'])
        ->name('admin.users.consolidate-balance.preview');
    Route::post('usuarios/{user}/retiro', [AdminUserDirectoryController::class, 'recordWithdrawal'])
        ->name('admin.users.withdrawal.store');
    Route::post('usuarios/{user}/referidos-progreso-manual', [AdminUserDirectoryController::class, 'addManualReferralProgress'])
        ->name('admin.users.manual-referral-progress');
    Route::post(
        'usuarios/{user}/balance-manual/{transaction}/revertir',
        [AdminUserDirectoryController::class, 'revertManualBalance'],
    )->name('admin.users.manual-balance.revert');

    Route::get('inversion', [InvestmentSettingsController::class, 'edit'])
        ->name('admin.investment-settings.edit');
    Route::put('inversion', [InvestmentSettingsController::class, 'update'])
        ->name('admin.investment-settings.update');

    Route::get('notificaciones', [AdminNotificationSettingsController::class, 'edit'])
        ->name('admin.notification-settings.edit');
    Route::put('notificaciones', [AdminNotificationSettingsController::class, 'update'])
        ->name('admin.notification-settings.update');

    Route::get('documentos-legales', [AdminLegalDocumentController::class, 'edit'])
        ->name('admin.legal-documents.edit');
    Route::put('documentos-legales', [AdminLegalDocumentController::class, 'update'])
        ->name('admin.legal-documents.update');

    Route::get('importacion-forex', [ForexImportStagingController::class, 'index'])
        ->name('admin.forex-import.index');
    Route::post('importacion-forex/aprobar', [ForexImportStagingController::class, 'approveUser'])
        ->name('admin.forex-import.approve');
    Route::post('importacion-forex/descartar-correo', [ForexImportStagingController::class, 'discardUser'])
        ->name('admin.forex-import.discard-email');
    Route::patch('importacion-forex/item/{forexImportStagingItem}', [ForexImportStagingController::class, 'update'])
        ->name('admin.forex-import.update');
    Route::delete('importacion-forex/item/{forexImportStagingItem}', [ForexImportStagingController::class, 'destroy'])
        ->name('admin.forex-import.destroy');
    Route::patch('importacion-forex/{forexImportStagingItem}/descartar', [ForexImportStagingController::class, 'discard'])
        ->name('admin.forex-import.discard');

    Route::get('inversiones', [InvestmentManageController::class, 'index'])
        ->name('admin.investments.index');
    Route::get('inversiones/{investment}/acreditaciones', [InvestmentManageController::class, 'accruals'])
        ->name('admin.investments.accruals');
    Route::patch('inversiones/{investment}/confirmar', [InvestmentManageController::class, 'confirm'])
        ->name('admin.investments.confirm');
    Route::patch('inversiones/{investment}/anular', [InvestmentManageController::class, 'void'])
        ->name('admin.investments.void');
    Route::patch('inversiones/{investment}/reactivar', [InvestmentManageController::class, 'reactivate'])
        ->name('admin.investments.reactivate');
    Route::patch('inversiones/{investment}/finalizar', [InvestmentManageController::class, 'finalize'])
        ->name('admin.investments.finalize');
    Route::get('inversiones/{investment}/referidos-pendientes', [InvestmentManageController::class, 'pendingReferrals'])
        ->name('admin.investments.pending-referrals');
    Route::post('inversiones/{investment}/referidos', [InvestmentManageController::class, 'applyReferrals'])
        ->name('admin.investments.apply-referrals');
    Route::get('acreditacion-mensual', [PlatformMonthlyAccrualController::class, 'index'])
        ->name('admin.platform-accrual.index');
    Route::get('acreditacion-mensual/{runDate}', [PlatformMonthlyAccrualController::class, 'show'])
        ->where('runDate', '[0-9]{4}-[0-9]{2}-[0-9]{2}')
        ->name('admin.platform-accrual.show');
    Route::post('acreditacion-mensual/ejecutar-prueba', [PlatformMonthlyAccrualController::class, 'runDebugAccrual'])
        ->name('admin.platform-accrual.debug-run');
    Route::get(
        'acreditacion-mensual/movimientos/{transaction}/recalcular',
        [PlatformMonthlyAccrualController::class, 'recalculatePreview'],
    )->name('admin.platform-accrual.recalculate-preview');
    Route::post(
        'acreditacion-mensual/movimientos/{transaction}/recalcular',
        [PlatformMonthlyAccrualController::class, 'recalculateApply'],
    )->name('admin.platform-accrual.recalculate-apply');
    Route::post(
        'acreditacion-mensual/{runDate}/anular',
        [PlatformMonthlyAccrualController::class, 'voidAccrualRun'],
    )->where('runDate', '[0-9]{4}-[0-9]{2}-[0-9]{2}')
        ->name('admin.platform-accrual.void-run');
    Route::get('acreditaciones/confirmar/{token}', [AccrualEmailConfirmationController::class, 'confirm'])
        ->name('admin.confirm.accrual');

    Route::get('debug', [AdminDebugController::class, 'index'])->name('admin.debug.index');
    Route::get('debug/secciones/inversiones', [AdminDebugController::class, 'sectionInvestments'])
        ->name('admin.debug.sections.investments');
    Route::get('debug/secciones/usuarios', [AdminDebugController::class, 'sectionUsers'])
        ->name('admin.debug.sections.users');
    Route::get('debug/secciones/ajustes-manuales', [AdminDebugController::class, 'sectionManualCredits'])
        ->name('admin.debug.sections.manual-credits');
    Route::get('debug/secciones/acreditaciones', [AdminDebugController::class, 'sectionAccruals'])
        ->name('admin.debug.sections.accruals');
    Route::get('debug/secciones/consolidacion-balance', [AdminDebugController::class, 'sectionBalanceConsolidation'])
        ->name('admin.debug.sections.balance-consolidation');
    Route::get('debug/consolidacion-balance/preview', [AdminDebugController::class, 'bulkConsolidateBalancePreview'])
        ->name('admin.debug.consolidate-balance.preview');
    Route::post('debug/consolidacion-balance', [AdminDebugController::class, 'bulkConsolidateBalance'])
        ->name('admin.debug.consolidate-balance');
    Route::post(
        'debug/usuarios/{user}/balance-manual/{transaction}/revertir',
        [AdminDebugController::class, 'revertManualBalance'],
    )->name('admin.debug.manual-balance.revert');

    Route::get('balances', [InvestmentBalancesController::class, 'index'])
        ->name('admin.balances.index');
    Route::get('retiros/solicitudes', [WithdrawalRequestManageController::class, 'index'])
        ->name('admin.withdrawals.requests.index');
    Route::patch(
        'retiros/solicitudes/{withdrawal_request}/aprobar',
        [WithdrawalRequestManageController::class, 'approve'],
    )->name('admin.withdrawals.requests.approve');
    Route::patch(
        'retiros/solicitudes/{withdrawal_request}/rechazar',
        [WithdrawalRequestManageController::class, 'reject'],
    )->name('admin.withdrawals.requests.reject');
    Route::get('retiros/historial', [WithdrawalHistoryController::class, 'index'])
        ->name('admin.withdrawals.history.index');

    Route::get('verificacion-kyc', [AdminKycReviewController::class, 'index'])
        ->name('admin.kyc.index');
    Route::get('verificacion-kyc/usuarios/{user}', [AdminKycReviewController::class, 'showSubmission'])
        ->name('admin.kyc.detail');
    Route::get(
        'verificacion-kyc/usuarios/{user}/archivos/{document}',
        AdminKycDocumentDownloadController::class,
    )->whereIn('document', ['front', 'back', 'selfie'])->name('admin.kyc.document-download');
    Route::patch('verificacion-kyc/usuarios/{user}/aprobar', [AdminKycReviewController::class, 'approve'])
        ->name('admin.kyc.approve');
    Route::patch('verificacion-kyc/usuarios/{user}/rechazar', [AdminKycReviewController::class, 'reject'])
        ->name('admin.kyc.reject');
});

require __DIR__.'/settings.php';
