# Payment Gateway Deployment Guide

This guide covers deploying the CloudLayer application with the optional Payment Gateway module.

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Environment Configuration](#environment-configuration)
3. [Build Options](#build-options)
4. [Deployment Scenarios](#deployment-scenarios)
5. [Monitoring & Maintenance](#monitoring--maintenance)
6. [Troubleshooting](#troubleshooting)

## Prerequisites

### System Requirements

- Elixir 1.14 or higher
- Erlang/OTP 24 or higher
- MySQL database
- Node.js 14+ (for asset compilation)
- Linux/Unix environment (recommended for production)

### Required Environment Variables

#### Main Application

```bash
# Database
DATABASE_URL=mysql://user:password@localhost/cloudlayer_prod
SECRET_KEY_BASE=your_secret_key_base_here

# Application
PHX_HOST=yourapp.com
PORT=4000
```

#### Payment Gateway (if enabled)

```bash
# Enable/Disable
INCLUDE_PAYMENT_GATEWAY=true  # Compile-time
ENABLE_PAYMENT_GATEWAY=true   # Runtime

# Provider Configuration
PG_API_KEY=your_api_key
PG_API_SECRET=your_api_secret
PG_API_ENDPOINT=https://api.payment-provider.com
PG_PROVIDER_MODULE=PaymentGatewayApp.Providers.YourProvider
```

## Environment Configuration

### Development

```bash
# .env.dev
export MIX_ENV=dev
export INCLUDE_PAYMENT_GATEWAY=true
export ENABLE_PAYMENT_GATEWAY=true
export PG_API_KEY=test_key
export PG_API_SECRET=test_secret
```

Load with: `source .env.dev`

### Staging

```bash
# .env.staging
export MIX_ENV=prod
export INCLUDE_PAYMENT_GATEWAY=true
export ENABLE_PAYMENT_GATEWAY=true
export DATABASE_URL=mysql://...
export SECRET_KEY_BASE=...
export PG_API_KEY=...
export PG_API_SECRET=...
export PG_API_ENDPOINT=https://staging-api.provider.com
```

### Production

```bash
# .env.prod
export MIX_ENV=prod
export INCLUDE_PAYMENT_GATEWAY=true
export ENABLE_PAYMENT_GATEWAY=true
export DATABASE_URL=mysql://...
export SECRET_KEY_BASE=...
export PG_API_KEY=...
export PG_API_SECRET=...
export PG_API_ENDPOINT=https://api.provider.com
export PG_PROVIDER_MODULE=PaymentGatewayApp.Providers.ProductionProvider
```

## Build Options

### Option 1: With Payment Gateway

```bash
# Set environment variables
export INCLUDE_PAYMENT_GATEWAY=true
export MIX_ENV=prod

# Get dependencies
mix deps.get --only prod

# Compile assets
npm install --prefix assets
npm install --prefix apps/payment_gateway_app/assets
mix assets.deploy

# Compile application
mix compile

# Create release
mix release
```

### Option 2: Without Payment Gateway

```bash
# Ensure PG is disabled
export INCLUDE_PAYMENT_GATEWAY=false
export MIX_ENV=prod

# Get dependencies
mix deps.get --only prod

# Compile assets (only main app)
npm install --prefix assets
mix assets.deploy

# Compile application
mix compile

# Create release
mix release
```

### Option 3: Docker Build

Create `Dockerfile`:

```dockerfile
FROM elixir:1.14-alpine AS builder

# Install build dependencies
RUN apk add --no-cache build-base git nodejs npm

WORKDIR /app

# Copy mix files
COPY mix.exs mix.lock ./
COPY config config

# Enable Payment Gateway at compile time
ENV INCLUDE_PAYMENT_GATEWAY=true
ENV MIX_ENV=prod

# Install dependencies
RUN mix local.hex --force && \
    mix local.rebar --force && \
    mix deps.get --only prod

# Copy source
COPY . .

# Compile assets
RUN mix assets.setup && mix assets.deploy

# Compile application and create release
RUN mix compile && \
    mix release

# Create runtime image
FROM alpine:3.18

RUN apk add --no-cache openssl ncurses-libs

WORKDIR /app

COPY --from=builder /app/_build/prod/rel/da_product_app ./

# Enable Payment Gateway at runtime
ENV ENABLE_PAYMENT_GATEWAY=true

CMD ["bin/da_product_app", "start"]
```

Build and run:

```bash
docker build -t cloudlayer:latest .
docker run -p 4000:4000 -p 4001:4001 \
  -e DATABASE_URL=... \
  -e SECRET_KEY_BASE=... \
  -e PG_API_KEY=... \
  cloudlayer:latest
```

## Deployment Scenarios

### Scenario 1: Full Deployment with Payment Gateway

```bash
# 1. Build release with PG
INCLUDE_PAYMENT_GATEWAY=true MIX_ENV=prod mix release

# 2. Deploy to server
scp -r _build/prod/rel/da_product_app user@server:/opt/cloudlayer/

# 3. Configure environment on server
ssh user@server
cat > /opt/cloudlayer/.env << EOF
ENABLE_PAYMENT_GATEWAY=true
DATABASE_URL=mysql://...
SECRET_KEY_BASE=...
PG_API_KEY=...
PG_API_SECRET=...
EOF

# 4. Start application
cd /opt/cloudlayer
source .env
./da_product_app/bin/da_product_app start
```

### Scenario 2: Main App Only (No Payment Gateway)

```bash
# 1. Build without PG
INCLUDE_PAYMENT_GATEWAY=false MIX_ENV=prod mix release

# 2. Deploy and start
# (No PG configuration needed)
./da_product_app/bin/da_product_app start
```

### Scenario 3: Enable PG Later Without Rebuild

If Payment Gateway was compiled but not enabled:

```bash
# On server, just enable runtime flag
export ENABLE_PAYMENT_GATEWAY=true

# Restart application
./da_product_app/bin/da_product_app restart
```

### Scenario 4: Gradual Rollout

1. **Phase 1**: Deploy with PG compiled but disabled
   ```bash
   INCLUDE_PAYMENT_GATEWAY=true
   ENABLE_PAYMENT_GATEWAY=false
   ```

2. **Phase 2**: Test PG on staging
   ```bash
   # On staging only
   ENABLE_PAYMENT_GATEWAY=true
   ```

3. **Phase 3**: Enable on production
   ```bash
   # After successful staging tests
   ENABLE_PAYMENT_GATEWAY=true
   ```

## Monitoring & Maintenance

### Health Checks

```bash
# Main app
curl http://localhost:4000/health

# Payment Gateway (if enabled)
curl http://localhost:4001/pgpayments
```

### Logging

Payment Gateway logs are integrated with the main application logs:

```bash
# View logs
tail -f /var/log/cloudlayer/app.log

# Filter PG logs
tail -f /var/log/cloudlayer/app.log | grep "PaymentGateway"
```

### Metrics

Monitor these key metrics:

- Payment initiation success rate
- Average payment processing time
- API response times
- Error rates

### Database Migrations

If adding PG-specific tables:

```bash
# Generate migration
mix ecto.gen.migration add_payment_gateway_tables

# Run migration
mix ecto.migrate
```

## Troubleshooting

### Issue: Payment Gateway not starting

**Symptoms**: PG routes return 404

**Solutions**:
1. Check compile-time flag: `INCLUDE_PAYMENT_GATEWAY=true`
2. Check runtime flag: `ENABLE_PAYMENT_GATEWAY=true`
3. Verify module is compiled: Check `_build/prod/lib/payment_gateway_app`
4. Check logs for startup errors

### Issue: Assets not loading

**Symptoms**: CSS/JS missing on PG pages

**Solutions**:
1. Ensure assets were compiled: `mix assets.deploy`
2. Check static file permissions
3. Verify nginx/reverse proxy configuration
4. Check browser console for 404 errors

### Issue: Provider configuration error

**Symptoms**: "Module not found" error

**Solutions**:
1. Verify `PG_PROVIDER_MODULE` format: `PaymentGatewayApp.Providers.YourProvider`
2. Ensure provider module is compiled
3. Check for typos in module name
4. Fallback to MockProvider for testing

### Issue: Port conflicts

**Symptoms**: "Address already in use"

**Solutions**:
1. Change PG port in `config/dev.exs` or `config/prod.exs`
2. Stop conflicting services
3. Use different ports: Main app (4000), PG (4001)

### Issue: Database connection errors

**Symptoms**: "Could not connect to database"

**Solutions**:
1. Verify DATABASE_URL format
2. Check database credentials
3. Ensure database exists
4. Check firewall rules
5. Verify SSL/TLS configuration

## Security Checklist

Before deploying to production:

- [ ] Change default secret keys
- [ ] Use environment variables for all secrets
- [ ] Enable HTTPS/TLS
- [ ] Configure firewall rules
- [ ] Set up rate limiting
- [ ] Enable request logging
- [ ] Configure CORS properly
- [ ] Use secure session configuration
- [ ] Enable CSRF protection
- [ ] Rotate API keys regularly
- [ ] Set up monitoring and alerts
- [ ] Configure backup strategy
- [ ] Document incident response plan

## Rollback Procedure

If issues arise after deployment:

```bash
# 1. Stop current version
./da_product_app/bin/da_product_app stop

# 2. Restore previous release
cp -r /opt/cloudlayer/releases/previous/* /opt/cloudlayer/

# 3. Restore environment configuration
cp /opt/cloudlayer/.env.backup /opt/cloudlayer/.env

# 4. Restart
source .env
./da_product_app/bin/da_product_app start

# 5. Verify
curl http://localhost:4000/health
```

## Support

For deployment assistance:
- Check the main README.md
- Review Payment Gateway README in `apps/payment_gateway_app/`
- Open an issue on GitHub
- Contact the DevOps team
