<?php

use App\Http\Controllers\ConfiguracionEmpresaController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\StorageLinkController;
use App\Http\Controllers\TokenController;
use App\Http\Controllers\UserController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes — Control Ganadero
|--------------------------------------------------------------------------
| Público: registro, tokens login/recuperación, configuración empresa.
| Autenticado (Sanctum): usuarios, roles, configuración, módulo /ranch.
*/

Route::get('/health', function () {
    return response()->json([
        'status' => 'ok',
        'app' => config('app.name'),
        'env' => app()->environment(),
        'time' => now()->toIso8601String(),
    ]);
});

/** Público: crea public/storage (artisan storage:link). Idempotente. */
Route::get('/storage-link', StorageLinkController::class)->middleware('throttle:10,1');

Route::post('/registro', [UserController::class, 'registro']);

Route::get('/configuracion-empresa/public', [ConfiguracionEmpresaController::class, 'publicConfig']);

Route::middleware('dev.setup')->group(function (): void {
    Route::get('/generate-key', function () {
        try {
            Artisan::call('key:generate');

            return response()->json([
                'success' => true,
                'message' => 'Clave de aplicación generada correctamente',
                'output' => Artisan::output(),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error generando clave de aplicación: '.$e->getMessage(),
            ], 500);
        }
    });
});

Route::prefix('/tokens')->group(function (): void {
    Route::post('/create', [TokenController::class, 'createToken'])->middleware('throttle:login');
    Route::post('/pw', [TokenController::class, 'createResetPW'])->middleware('throttle:login');
    Route::post('/savepw', [TokenController::class, 'saveResetPW']);
    Route::post('/getpwuuid', [TokenController::class, 'getUserUuid']);
});

Route::prefix('/configuracion-empresa')->group(function (): void {
    Route::get('/', [ConfiguracionEmpresaController::class, 'index']);
});

Route::middleware('auth:sanctum')->group(function () {

    Route::prefix('/tokens')->group(function (): void {
        Route::post('/logout', [TokenController::class, 'logout']);
        Route::delete('/{token}', [TokenController::class, 'expire']);
        Route::get('/permissions', function () {
            if (! auth()->check()) {
                return response()->json(['all' => false, 'permissions' => []], 401);
            }

            /** @var \App\Models\User $user */
            $user = auth()->user();
            $roles = $user->getRoleNames('web')->toArray();
            $permissions = $user->getAllPermissions()->pluck('name')->toArray();

            return response()->json([
                'all' => in_array(\App\Models\User::ADMIN_ROL, $roles, true),
                'permissions' => $permissions,
                'roles' => $roles,
            ]);
        });
    });

    Route::prefix('/users')->group(function (): void {
        Route::get('/', function (Request $request) {
            $user = $request->user()?->load('roles');
            if ($user === null) {
                return response()->json(['message' => 'No autenticado.'], 401);
            }

            return response()->json(['data' => $user]);
        });
        Route::get('/all', [UserController::class, 'getUsers']);
        Route::get('/{user}', [UserController::class, 'getUser']);
        Route::post('/create', [UserController::class, 'store']);
        Route::put('/{user}/edit', [UserController::class, 'update']);
        Route::put('/{user}/password', [UserController::class, 'updatePassword']);
        Route::put('/perfil', [UserController::class, 'updatePerfil']);
        Route::delete('/{user}', [UserController::class, 'destroy']);
    });

    Route::prefix('/roles')->group(function (): void {
        Route::get('/all', [RoleController::class, 'getRoles']);
        Route::get('/permissions', [RoleController::class, 'getPermissions']);
        Route::put('/{role}/permissions', [RoleController::class, 'updateRolePermissions']);
    });

    Route::prefix('/configuracion-empresa')->middleware('permission:administracion.usuarios')->group(function (): void {
        Route::put('/update', [ConfiguracionEmpresaController::class, 'update']);
        Route::post('/upload-logo', [ConfiguracionEmpresaController::class, 'uploadLogo']);
        Route::post('/upload-favicon', [ConfiguracionEmpresaController::class, 'uploadFavicon']);
        Route::post('/upload-icono-mensaje', [ConfiguracionEmpresaController::class, 'uploadIconoMensaje']);
        Route::delete('/delete-logo', [ConfiguracionEmpresaController::class, 'deleteLogo']);
        Route::delete('/delete-favicon', [ConfiguracionEmpresaController::class, 'deleteFavicon']);
        Route::delete('/delete-icono-mensaje', [ConfiguracionEmpresaController::class, 'deleteIconoMensaje']);
    });

    require __DIR__.'/ranch.php';
});
