<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\ScawattController;
use App\Http\Controllers\ScawattValorController;
use App\Http\Controllers\UsuarioController;
use App\Http\Controllers\TransaccionController;
use App\Http\Controllers\MarketplaceController;
use App\Http\Controllers\MensajeController;
use App\Http\Controllers\NotificacionController;
use App\Http\Controllers\ConfiguracionController;
use App\Http\Controllers\DatosBancariosController;

/*
|--------------------------------------------------------------------------
| API Routes - Sistema ScaWatts
|--------------------------------------------------------------------------
|
| Organización:
| - Rutas de autenticación (login, register, logout)
| - Rutas públicas (sin autenticación)
| - Rutas de usuario (requieren autenticación)
| - Rutas de administrador (requieren auth + rol admin)
|
*/

// ============================================================================
// AUTENTICACIÓN (Rutas públicas de auth)
// ============================================================================

Route::prefix('auth')->group(function () {
    Route::post('/login', [AuthController::class, 'login']);
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/google', [AuthController::class, 'googleAuth']);
    Route::post('/apple', [AuthController::class, 'appleAuth']);
    Route::post('/forgot-password', [AuthController::class, 'forgotPassword']);
    Route::post('/reset-password', [AuthController::class, 'resetPassword']);
    
    // Rutas protegidas de auth
    Route::middleware(['auth.api'])->group(function () {
        Route::post('/logout', [AuthController::class, 'logout']);
        Route::get('/user', [AuthController::class, 'user']);
        Route::post('/change-password', [AuthController::class, 'changePassword']);
    });
});

// ============================================================================
// RUTAS PÚBLICAS (Sin autenticación)
// ============================================================================

Route::prefix('public')->group(function () {
    // ScaWatts - Listado público
    Route::get('/scawatts', [ScawattController::class, 'index']);
    Route::get('/scawatts/{id}/proyeccion', [ScawattController::class, 'obtenerProyeccion']);
    Route::get('/scawatts/{identifier}/documentos', [ScawattController::class, 'documentosPublicos']);
    Route::post('/scawatts/{identifier}/documentos/solicitar', [ScawattController::class, 'solicitarDocumentos']);
    Route::post('/scawatts/{identifier}/documentos/verificar', [ScawattController::class, 'verificarCodigoDocumentos']);
    
    // Marketplace - Listado público de ScaWatts en venta
    Route::get('/marketplace', [MarketplaceController::class, 'listar']);
});

// ============================================================================
// TEMPORAL: Endpoints sin autenticación para desbloquear frontend
// IMPORTANTE: Frontend debe arreglar su interceptor HTTP para enviar el header:
// Authorization: Bearer {token}
// Una vez arreglado, mover estas rutas de vuelta al grupo auth.api
// ============================================================================

Route::get('/weather/current', [\App\Http\Controllers\WeatherController::class, 'current']);
Route::get('/solar/current', [\App\Http\Controllers\SolarController::class, 'current']);

// TEMPORAL: Valorización sin auth para pruebas
Route::get('/usuarios/{id}/valorizacion', [UsuarioController::class, 'valorizacion']);

// SCAWATT - Valores en tiempo real e historial (públicos para portafolio)
Route::prefix('scawatt')->group(function () {
    Route::get('/valor-actual', [ScawattValorController::class, 'valorActual']);
    Route::get('/historial', [ScawattValorController::class, 'historial']);
    Route::get('/estadisticas-dia', [ScawattValorController::class, 'estadisticasDia']);
});

// ============================================================================
// RUTAS DE USUARIO (Requieren autenticación)
// TODO: Agregar middleware: Route::middleware(['auth:sanctum'])->group(...)
// ============================================================================

// USUARIOS - Gestión de perfil y tokens FCM
Route::prefix('usuarios')->group(function () {
    Route::get('/{id}/datos-bancarios', [DatosBancariosController::class, 'mostrar']);
    Route::post('/{id}/datos-bancarios', [DatosBancariosController::class, 'guardar']);
    Route::get('/{id}/cedula-fotos', [DatosBancariosController::class, 'cedula']);
    Route::post('/{id}/cedula-fotos', [DatosBancariosController::class, 'subirCedula']);
    Route::get('/{id}/perfil', [UsuarioController::class, 'obtenerPerfil']);
    Route::put('/{id}/perfil', [UsuarioController::class, 'actualizarPerfil']);
    Route::post('/{id}/avatar/upload', [UsuarioController::class, 'subirAvatar']);
    Route::get('/{id}/scawatts', [ScawattController::class, 'listarPorUsuario']);
    Route::get('/{id}/dashboard', [UsuarioController::class, 'dashboard']);
    Route::get('/{id}/movimientos', [UsuarioController::class, 'movimientos']);
    Route::get('/{id}/movimientos/pdf', [UsuarioController::class, 'movimientosPDF']);
    Route::get('/{id}/retiros/resumen', [UsuarioController::class, 'resumenRetiros']);
    Route::get('/{id}/scawatts/estadisticas', [ScawattController::class, 'estadisticasUsuario']);
    Route::post('/{id}/register-token', [UsuarioController::class, 'registrarTokenFCM']);
    Route::delete('/{id}/unregister-token', [UsuarioController::class, 'eliminarTokenFCM']);
});

Route::get('/scawatts/{id}/proyeccion', [ScawattController::class, 'obtenerProyeccion'])->middleware('auth.api');

// MENSAJES - Sistema de mensajería interna
Route::prefix('mensajes')->group(function () {
    Route::get('/{usuarioId}/bandeja-entrada', [MensajeController::class, 'bandejaEntrada']);
    Route::get('/{usuarioId}/enviados', [MensajeController::class, 'enviados']);
    Route::get('/{usuarioId}/no-leidos', [MensajeController::class, 'contarNoLeidos']);
    Route::get('/{id}', [MensajeController::class, 'show']);
    Route::post('/', [MensajeController::class, 'store']);
    Route::post('/{id}/responder', [MensajeController::class, 'responder']);
    Route::put('/{id}/leer', [MensajeController::class, 'marcarLeido']);
    Route::delete('/{id}', [MensajeController::class, 'destroy']);
});

// NOTIFICACIONES - Sistema de notificaciones
Route::prefix('notificaciones')->group(function () {
    Route::get('/{usuarioId}', [NotificacionController::class, 'index']);
    Route::get('/{usuarioId}/no-leidas', [NotificacionController::class, 'contarNoLeidas']);
    Route::get('/{usuarioId}/badge', [NotificacionController::class, 'contarNoLeidas']); // Alias para frontend
    Route::put('/{id}/leer', [NotificacionController::class, 'marcarLeida']);
    Route::put('/{usuarioId}/leer-todas', [NotificacionController::class, 'marcarTodasLeidas']);
    Route::delete('/{id}', [NotificacionController::class, 'destroy']);
});

// TRANSACCIONES - Depósitos y Retiros del usuario
Route::prefix('transacciones')->group(function () {
    // Depósitos
    Route::post('/depositos', [TransaccionController::class, 'crearDeposito']);
    
    // Retiros
    Route::post('/retiros', [TransaccionController::class, 'solicitarRetiro']);
});

// Alias legacy para apps que aún llaman /api/admin/retiros (sin autenticación)
Route::post('/admin/retiros', [TransaccionController::class, 'solicitarRetiro']);
Route::post('/admin/scawatts/solicitar-contacto', [ScawattController::class, 'solicitarContacto']);

// MARKETPLACE - Compraventa de ScaWatts
Route::prefix('marketplace')->group(function () {
    Route::get('/', [MarketplaceController::class, 'listar']);
    Route::get('/mis-publicaciones/{usuarioId}', [MarketplaceController::class, 'misPublicaciones']);
    Route::get('/mis-compras/{usuarioId}', [MarketplaceController::class, 'misCompras']);
    Route::post('/publicar', [MarketplaceController::class, 'publicar']);
    Route::post('/{id}/comprar', [MarketplaceController::class, 'comprar']);
    Route::put('/{id}/retirar', [MarketplaceController::class, 'retirar']);
    
    // Debug: Obtener ScaWatts disponibles para publicar
    Route::get('/debug/seriales-disponibles/{usuarioId}', [MarketplaceController::class, 'serialesDisponibles']);
});

// ============================================================================
// RUTAS DE ADMINISTRADOR (Requieren autenticación)
// ============================================================================

Route::middleware(['auth.api'])->prefix('admin')->group(function () {
    
    // SCAWATTS - Gestión de ScaWatts
    Route::prefix('scawatts')->group(function () {
        Route::get('/', [ScawattController::class, 'index']);
        Route::get('/estadisticas', [ScawattController::class, 'estadisticas']);
        Route::post('/crear', [ScawattController::class, 'crear']);
        Route::get('/sync', [ScawattController::class, 'sincronizar']);
    });
    
    // USUARIOS - CRUD completo
    Route::prefix('usuarios')->group(function () {
        Route::get('/', [UsuarioController::class, 'index']);
        Route::get('/estadisticas', [UsuarioController::class, 'estadisticas']);
        Route::get('/{id}', [UsuarioController::class, 'show']);
        Route::post('/', [UsuarioController::class, 'store']);
        Route::put('/{id}', [UsuarioController::class, 'update']);
        Route::put('/{id}/estado', [UsuarioController::class, 'cambiarEstado']);
        // Ruta para detalle de usuario (sin auth para permitir acceso web)
        Route::get('/{id}/detalle', [UsuarioController::class, 'detalle'])->withoutMiddleware(['auth.api']);
    });
    
    // TRANSACCIONES - Gestión de depósitos y retiros
    Route::prefix('transacciones')->group(function () {
        Route::get('/estadisticas', [TransaccionController::class, 'estadisticas']);
        
        // Depósitos
        Route::get('/depositos', [TransaccionController::class, 'listarDepositos']);
        Route::put('/depositos/{id}/aprobar', [TransaccionController::class, 'aprobarDeposito']);
        Route::put('/depositos/{id}/rechazar', [TransaccionController::class, 'rechazarDeposito']);
        
        // Retiros
        Route::get('/retiros', [TransaccionController::class, 'listarRetiros']);
        Route::put('/retiros/{id}/aprobar', [TransaccionController::class, 'aprobarRetiro']);
        Route::put('/retiros/{id}/rechazar', [TransaccionController::class, 'rechazarRetiro']);
    });
    
    // MARKETPLACE - Gestión y estadísticas
    Route::prefix('marketplace')->group(function () {
        Route::get('/estadisticas', [MarketplaceController::class, 'estadisticas']);
    });
    
    // NOTIFICACIONES - Envío masivo
    Route::prefix('notificaciones')->group(function () {
        Route::post('/', [NotificacionController::class, 'store']);
        Route::post('/masiva', [NotificacionController::class, 'notificacionMasiva']);
    });
    
    // CONFIGURACIÓN - Parámetros del sistema
    Route::prefix('configuracion')->group(function () {
        Route::get('/', [ConfiguracionController::class, 'ver']);
        Route::get('/grupos', [ConfiguracionController::class, 'listarGrupos']);
        Route::get('/grupo/{grupo}', [ConfiguracionController::class, 'porGrupo']);
        Route::get('/{clave}', [ConfiguracionController::class, 'obtener']);
        Route::post('/', [ConfiguracionController::class, 'crear']);
        Route::put('/{clave}', [ConfiguracionController::class, 'actualizar']);
        Route::put('/actualizar-multiple', [ConfiguracionController::class, 'actualizarMultiple']);
        Route::delete('/{clave}', [ConfiguracionController::class, 'eliminar']);
    });
});

// ============================================================================
// DATOS METEOROLÓGICOS Y SOLARES
// NOTA: Movidos arriba como rutas públicas (líneas 68-69)
// ============================================================================

// ============================================================================
// MONITOR SERVIDOR - Verificación de procesos
// ============================================================================

Route::middleware(['auth.api', 'auth.master'])->prefix('monitor')->group(function () {
    Route::get('/procesos', [\App\Http\Controllers\MonitorController::class, 'obtenerProcesos']);
});
