# Guía de Deployment - Galappxy

## 📋 Pre-requisitos

- Servidor Linux (Ubuntu 22.04 LTS recomendado)
- PHP 8.1 o superior
- MySQL 8.0+ o AWS Aurora MySQL
- Apache 2.4+ o Nginx
- Composer
- Git
- Certificados SSL (Let's Encrypt o comercial)

## 🚀 Deployment Paso a Paso

### 1. Preparar Servidor

```bash
# Actualizar sistema
sudo apt update && sudo apt upgrade -y

# Instalar PHP 8.1 y extensiones
sudo apt install -y php8.1 php8.1-fpm php8.1-mysql php8.1-mbstring \
    php8.1-xml php8.1-curl php8.1-gd php8.1-zip php8.1-bcmath

# Instalar Apache
sudo apt install -y apache2
sudo a2enmod rewrite ssl headers

# O instalar Nginx
# sudo apt install -y nginx

# Instalar Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
```

### 2. Clonar Repositorio

```bash
# Crear directorio web
sudo mkdir -p /var/www/galappxy
sudo chown -R www-data:www-data /var/www/galappxy

# Clonar (como www-data)
sudo -u www-data git clone https://github.com/tu-org/galappxy.git /var/www/galappxy
cd /var/www/galappxy
```

### 3. Configurar Variables de Entorno

```bash
# Copiar templates
cp .env.example .env_auth
cp .env.example .env_audit
cp .env.example .env_core

# Editar con credenciales reales
nano .env_auth
nano .env_audit
nano .env_core

# IMPORTANTE: Permisos seguros
chmod 600 .env_*
chown www-data:www-data .env_*
```

**Configuración mínima en .env_auth:**
```bash
DB_WRITER_DSN="mysql:host=tu-aurora.rds.amazonaws.com;port=3306;dbname=galappxy_auth;charset=utf8mb4"
DB_WRITER_USER="galappxy_auth_writer"
DB_WRITER_PASS="tu-password-seguro"

DB_READER_DSN="mysql:host=tu-aurora-ro.rds.amazonaws.com;port=3306;dbname=galappxy_auth;charset=utf8mb4"
DB_READER_USER="galappxy_auth_reader"
DB_READER_PASS="tu-password-seguro"

TENANT_FILTERING_ENABLED=true
TENANT_FILTERING_STRICT=false

AUDIT_ENABLE=true

JWT_ISSUER="auth-api.galappxy.com"
JWT_AUDIENCE="galappxy.com"
```

### 4. Crear Bases de Datos

```bash
# Conectar a Aurora/MySQL
mysql -h tu-aurora.cluster-xxxxx.rds.amazonaws.com -u admin -p

# Crear bases de datos
CREATE DATABASE galappxy_core CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE galappxy_auth CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE galappxy_audit CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

# Crear usuarios por servicio
CREATE USER 'galappxy_auth_writer'@'%' IDENTIFIED BY 'password-seguro-1';
CREATE USER 'galappxy_auth_reader'@'%' IDENTIFIED BY 'password-seguro-2';
GRANT SELECT, INSERT, UPDATE, DELETE ON galappxy_auth.* TO 'galappxy_auth_writer'@'%';
GRANT SELECT ON galappxy_auth.* TO 'galappxy_auth_reader'@'%';

CREATE USER 'galappxy_audit_writer'@'%' IDENTIFIED BY 'password-seguro-3';
CREATE USER 'galappxy_audit_reader'@'%' IDENTIFIED BY 'password-seguro-4';
GRANT SELECT, INSERT, UPDATE, DELETE ON galappxy_audit.* TO 'galappxy_audit_writer'@'%';
GRANT SELECT ON galappxy_audit.* TO 'galappxy_audit_reader'@'%';

# Aplicar cambios
FLUSH PRIVILEGES;
EXIT;

# Importar schemas
mysql -h tu-aurora... -u admin -p galappxy_core < database/schemas/galappxy_core.sql
mysql -h tu-aurora... -u admin -p galappxy_auth < database/schemas/galappxy_auth.sql
mysql -h tu-aurora... -u admin -p galappxy_audit < database/schemas/galappxy_audit.sql
```

### 5. Generar Llaves JWT (RSA)

```bash
# Crear directorio para llaves
sudo mkdir -p /var/www/galappxy/storage/keys
cd /var/www/galappxy/storage/keys

# Generar llave privada
openssl genrsa -out private_key.pem 2048

# Extraer llave pública
openssl rsa -in private_key.pem -pubout -out public_key.pem

# Permisos seguros
chmod 600 private_key.pem
chmod 644 public_key.pem
chown -R www-data:www-data /var/www/galappxy/storage

# Actualizar rutas en .env_auth
# JWT_PRIVATE_KEY_PATH="/var/www/galappxy/storage/keys/private_key.pem"
# JWT_PUBLIC_KEY_PATH="/var/www/galappxy/storage/keys/public_key.pem"
```

### 6. Configurar Apache

```bash
# Crear VirtualHost para auth-api
sudo nano /etc/apache2/sites-available/auth-api.conf
```

```apache
<VirtualHost *:80>
    ServerName auth-api.galappxy.com
    Redirect permanent / https://auth-api.galappxy.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName auth-api.galappxy.com
    DocumentRoot /var/www/galappxy/services/auth-api
    
    <Directory /var/www/galappxy/services/auth-api>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
        
        # Seguridad adicional
        <FilesMatch "^\.">
            Require all denied
        </FilesMatch>
    </Directory>
    
    # Logs
    ErrorLog ${APACHE_LOG_DIR}/auth-api-error.log
    CustomLog ${APACHE_LOG_DIR}/auth-api-access.log combined
    
    # SSL
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/auth-api.galappxy.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/auth-api.galappxy.com/privkey.pem
    
    # Seguridad SSL
    SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
    SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
    SSLHonorCipherOrder off
    
    # HSTS
    Header always set Strict-Transport-Security "max-age=63072000"
</VirtualHost>
```

```bash
# Crear VirtualHost para audit-api (similar)
sudo nano /etc/apache2/sites-available/audit-api.conf

# Habilitar sitios
sudo a2ensite auth-api audit-api

# Test configuración
sudo apache2ctl configtest

# Reiniciar Apache
sudo systemctl restart apache2
```

### 7. Configurar SSL con Let's Encrypt

```bash
# Instalar Certbot
sudo apt install -y certbot python3-certbot-apache

# Obtener certificados
sudo certbot --apache -d auth-api.galappxy.com
sudo certbot --apache -d audit-api.galappxy.com
sudo certbot --apache -d core-api.galappxy.com

# Auto-renovación
sudo certbot renew --dry-run
```

### 8. Crear .htaccess en cada servicio

```bash
# /var/www/galappxy/services/auth-api/.htaccess
cat > /var/www/galappxy/services/auth-api/.htaccess << 'EOF'
# Enable Rewrite Engine
RewriteEngine On

# Disable directory listing
Options -Indexes

# Route all requests to index.php if file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

# Security Headers
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "DENY"
    Header set X-XSS-Protection "1; mode=block"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# Hide .env files
<FilesMatch "^\.env">
    Require all denied
</FilesMatch>
EOF

# Copiar a otros servicios
cp /var/www/galappxy/services/auth-api/.htaccess /var/www/galappxy/services/audit-api/
cp /var/www/galappxy/services/auth-api/.htaccess /var/www/galappxy/services/core-api/
```

### 9. Testing

```bash
# Test auth-api
curl https://auth-api.galappxy.com/v1/auth/domain \
  -H "Content-Type: application/json" \
  -d '{"payload":{"host":"login.galappxy.com"}}'

# Debería devolver info del dominio o error controlado
```

### 10. Monitoreo Post-Deployment

```bash
# Ver logs en tiempo real
sudo tail -f /var/log/apache2/auth-api-error.log

# Verificar queries de audit
mysql -h tu-aurora... -u admin -p galappxy_audit

SELECT app, COUNT(*) as queries, AVG(duration_ms) as avg_ms
FROM SQL_LOG
WHERE ts >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)
GROUP BY app;
```

## 🔒 Checklist de Seguridad Post-Deployment

- [ ] Archivos .env con permisos 600
- [ ] SSL/TLS configurado correctamente (A+ en ssllabs.com)
- [ ] Headers de seguridad configurados
- [ ] Firewall configurado (solo 80, 443 abiertos)
- [ ] Usuarios de BD con permisos mínimos
- [ ] Backups automáticos configurados
- [ ] Monitoreo de logs activo
- [ ] TENANT_FILTERING_ENABLED=true
- [ ] Rate limiting configurado

## 📊 Monitoreo Continuo

```sql
-- Dashboard básico de salud
-- Queries lentas (última hora)
SELECT app, sql_hash, AVG(duration_ms) as avg_ms, COUNT(*) as count
FROM galappxy_audit.SQL_LOG
WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
  AND duration_ms > 1000
GROUP BY app, sql_hash
ORDER BY avg_ms DESC
LIMIT 10;

-- Errores recientes
SELECT app, event_key, COUNT(*) as error_count
FROM galappxy_audit.AUDIT
WHERE has_error = 1
  AND ts >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
GROUP BY app, event_key
ORDER BY error_count DESC;
```

## 🆘 Rollback

Si algo sale mal:

```bash
# Mantener versión anterior en branch
git checkout production-stable

# Restaurar .env anteriores (tener backup)
cp .env_auth.backup .env_auth

# Reiniciar servicios
sudo systemctl restart apache2

# Verificar logs
sudo tail -f /var/log/apache2/error.log
```
