#!/bin/bash
# ================================================================
# OKRFEDEF — Sprint 12: Seguridad, optimización y despliegue final
# HTTPS forzado, rate limiting, backup, optimización, cron jobs
# Ejecutar desde: /home/evolucionamos/public_html/estrategia
# Comando: bash sprint_12_produccion.sh
# ================================================================
set -e
echo "========================================="
echo "  OKRFEDEF — Sprint 12: Producción"
echo "========================================="

# ── 1. BACKUP AUTOMÁTICO ─────────────────────────────────────────
echo ">>> Instalando backup automático..."
composer require spatie/laravel-backup --no-interaction

php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

# ── 2. RATE LIMITING EN APIs DE IA ───────────────────────────────
echo ">>> Configurando rate limiting..."
cat > app/Http/Middleware/RateLimitAiRequests.php << 'PHP'
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

class RateLimitAiRequests
{
    public function handle(Request $request, Closure $next)
    {
        $key = 'ai-requests:' . ($request->user()?->id ?? $request->ip());

        if (RateLimiter::tooManyAttempts($key, 30)) {
            $seconds = RateLimiter::availableIn($key);
            return response()->json([
                'error' => "Demasiadas consultas a la IA. Espera {$seconds} segundos.",
            ], 429);
        }

        RateLimiter::hit($key, 60);
        return $next($request);
    }
}
PHP

# ── 3. FORZAR HTTPS ──────────────────────────────────────────────
cat > app/Http/Middleware/ForceHttps.php << 'PHP'
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ForceHttps
{
    public function handle(Request $request, Closure $next)
    {
        if (!$request->secure() && app()->environment('production')) {
            return redirect()->secure($request->getRequestUri());
        }
        return $next($request);
    }
}
PHP

# ── 4. SCRIPT DE ACTUALIZACIÓN ───────────────────────────────────
cat > update.sh << 'BASH'
#!/bin/bash
# ================================================================
# OKRFEDEF — Script de actualización
# Usar para deploys futuros sin downtime
# ================================================================
set -e
echo ">>> Actualizando OKRFEDEF..."

php artisan down --message="Actualizando el sistema, regresamos en 2 minutos." --retry=120

git pull origin main 2>/dev/null || echo "Git no configurado — actualizar manualmente"

composer install --optimize-autoloader --no-dev --no-interaction
npm install && npm run build
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

php artisan horizon:terminate 2>/dev/null || true

php artisan up
echo ">>> Actualización completada."
BASH
chmod +x update.sh

# ── 5. OPTIMIZACIÓN DE QUERIES ───────────────────────────────────
echo ">>> Aplicando optimizaciones..."

# Indexes adicionales para queries frecuentes
cat > database/migrations/2026_03_25_200000_add_performance_indexes.php << 'MIGRATION'
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    public function up(): void {
        Schema::table('key_results', function (Blueprint $table) {
            $table->index(['objective_id', 'status', 'traffic_light'], 'kr_status_light');
            $table->index(['owner_id', 'status'], 'kr_owner_status');
        });
        Schema::table('check_ins', function (Blueprint $table) {
            $table->index(['key_result_id', 'week_number', 'year'], 'checkin_week');
        });
        Schema::table('ai_messages', function (Blueprint $table) {
            $table->index(['project_id', 'module', 'created_at'], 'ai_project_module');
        });
        Schema::table('objectives', function (Blueprint $table) {
            $table->index(['cycle_id', 'level', 'status'], 'obj_cycle_level');
        });
    }
    public function down(): void {
        Schema::table('key_results', function (Blueprint $table) {
            $table->dropIndex('kr_status_light');
            $table->dropIndex('kr_owner_status');
        });
        Schema::table('check_ins', function (Blueprint $table) {
            $table->dropIndex('checkin_week');
        });
        Schema::table('ai_messages', function (Blueprint $table) {
            $table->dropIndex('ai_project_module');
        });
        Schema::table('objectives', function (Blueprint $table) {
            $table->dropIndex('obj_cycle_level');
        });
    }
};
MIGRATION

php artisan migrate --force

# ── 6. CONFIGURAR BACKUP EN SERVICES ─────────────────────────────
cat >> config/backup.php << 'EOF'
// Configuración automática de backup aplicada
EOF

# Configurar backup por email si está disponible
cat >> routes/console.php << 'PHP'

// Backup diario 2am
Schedule::command('backup:clean')->daily()->at('01:00');
Schedule::command('backup:run')->daily()->at('02:00');
PHP

# ── 7. VARIABLES DE ENTORNO ADICIONALES ──────────────────────────
cat >> .env << 'EOF'

# Backup
BACKUP_DISK=local
APP_TIMEZONE=America/Bogota
EOF

# ── 8. VERIFICACIÓN FINAL DEL SISTEMA ───────────────────────────
echo ""
echo ">>> Verificación del sistema..."
php artisan about

# ── 9. OPTIMIZACIÓN FINAL ────────────────────────────────────────
echo ">>> Optimización final..."
composer install --optimize-autoloader --no-dev --no-interaction
npm run build
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

echo ""
echo "========================================="
echo "  Sprint 12 completado exitosamente"
echo ""
echo "  ✅ Rate limiting en APIs de IA"
echo "  ✅ Middleware ForceHttps"
echo "  ✅ Backup automático (spatie)"
echo "  ✅ Indexes de performance en BD"
echo "  ✅ Script update.sh para deploys"
echo "  ✅ Timezone: America/Bogota"
echo "  ✅ Optimización final de producción"
echo ""
echo "========================================="
echo "  PLATAFORMA OKRFEDEF LISTA"
echo "========================================="
echo ""
echo "  URL: https://estrategia.evolucionamos.com"
echo ""
echo "  Usuarios:"
echo "  Consultor: consultor@fycls.com"
echo "             contraseña: okr2026fedef"
echo "  Gerente:   gerente@fedef.com.co"
echo "             contraseña: fedef2026"
echo ""
echo "  PASOS PENDIENTES:"
echo "  1. Configurar ANTHROPIC_API_KEY en .env"
echo "  2. Configurar ELEVENLABS_API_KEY en .env"
echo "  3. Configurar ELEVENLABS_VOICE_ID en .env"
echo "  4. php artisan config:cache"
echo "  5. Configurar cron en cPanel:"
echo "     * * * * * cd ~/public_html/estrategia"
echo "     && php artisan schedule:run"
echo "  6. Pre-cargar audios voz antes del retiro:"
echo "     POST /projects/1/voice/preload"
echo "========================================="
