# Payment Service Deployment Guide

This guide explains how to deploy the Go Payment Service to production on `https://payment.taifaguard.co.ke` using nginx and systemd.

## Prerequisites

- Ubuntu/Debian server with root/sudo access
- Go 1.21+ installed
- PostgreSQL server installed and running
- Redis server installed and running
- Nginx installed
- SSL certificate for payment.taifaguard.co.ke
- Domain DNS pointing to your server IP

## Step 1: Prepare the Server

### 1.1 Create necessary directories

```bash
sudo mkdir -p /var/www/html/internet/payment
sudo mkdir -p /var/log/payment
sudo chown -R www-data:www-data /var/www/html/internet/payment
sudo chown -R www-data:www-data /var/log/payment
```

### 1.2 Upload project files

Upload your project files to `/var/www/html/internet/payment/` or clone from your repository:

```bash
cd /var/www/html/internet/payment
# Upload files here or git clone
```

## Step 2: Install Go (if not already installed)

```bash
# Download Go (check for latest version at https://golang.org/dl/)
wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz

# Remove old Go installation if exists
sudo rm -rf /usr/local/go

# Extract Go
sudo tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz

# Add Go to PATH (add to ~/.bashrc or /etc/profile)
export PATH=$PATH:/usr/local/go/bin

# Verify installation
go version
```

## Step 3: Set Up PostgreSQL Database

### 3.1 Install PostgreSQL (if not installed)

```bash
sudo apt update
sudo apt install postgresql postgresql-contrib
sudo systemctl start postgresql
sudo systemctl enable postgresql
```

### 3.2 Create Database and User

```bash
sudo -u postgres psql
```

In the PostgreSQL prompt, run:

```sql
CREATE DATABASE internet;
CREATE USER payment_user WITH PASSWORD 'your_secure_password_here';
ALTER ROLE payment_user SET client_encoding TO 'utf8';
ALTER ROLE payment_user SET default_transaction_isolation TO 'read committed';
ALTER ROLE payment_user SET timezone TO 'UTC';
GRANT ALL PRIVILEGES ON DATABASE internet TO payment_user;
\q
```

## Step 4: Set Up Redis (if not installed)

```bash
sudo apt install redis-server
sudo systemctl start redis-server
sudo systemctl enable redis-server

# Test Redis
redis-cli ping
```

## Step 5: Build the Application

```bash
cd /var/www/html/internet/payment

# Update dependencies
go mod tidy
go get gorm.io/driver/postgres@latest

# Build the application
go build -o payment-service .

# Make it executable
chmod +x payment-service
```

## Step 6: Configure Environment Variables

### 6.1 Create .env file

```bash
cd /var/www/html/internet/payment
cp env.example .env
nano .env
```

Update the `.env` file with your actual values:

```env
# Database Configuration (PostgreSQL)
DB_HOST=localhost
DB_PORT=5432
DB_USER=payment_user
DB_PASSWORD=your_secure_password_here
DB_NAME=internet
DB_SSL_MODE=disable

# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0

# Server Configuration
SERVER_PORT=8080
SERVER_HOST=0.0.0.0
GIN_MODE=release

# JWT Configuration
JWT_SECRET=your_jwt_secret_key_here_make_it_long_and_secure

# Connection Pool
DB_MAX_OPEN_CONNS=100
DB_MAX_IDLE_CONNS=10
DB_CONN_MAX_LIFETIME=1h
```

## Step 7: Set Up SSL Certificate

### Option A: Using Let's Encrypt (Recommended)

```bash
sudo apt update
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d payment.taifaguard.co.ke
```

This will automatically configure nginx with SSL certificates.

### Option B: Using Your Own Certificates

Place your SSL certificate and key in:
- Certificate: `/etc/ssl/certs/payment.taifaguard.co.ke.crt`
- Key: `/etc/ssl/private/payment.taifaguard.co.ke.key`

## Step 8: Configure Nginx

### 8.1 Add rate limiting zones to nginx.conf

```bash
sudo nano /etc/nginx/nginx.conf
```

Add these lines in the `http` block (before any `server` blocks):

```nginx
http {
    # ... existing configuration ...
    
    # Rate limiting zones
    limit_req_zone $binary_remote_addr zone=api:10m rate=100r/m;
    limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
    limit_req_zone $binary_remote_addr zone=payment:10m rate=20r/m;
    
    # ... rest of configuration ...
}
```

### 8.2 Copy nginx configuration

```bash
sudo cp /var/www/html/internet/payment/nginx-payment.conf /etc/nginx/sites-available/payment.taifaguard.co.ke
```

### 8.3 Update SSL certificate paths (if using Let's Encrypt)

```bash
sudo nano /etc/nginx/sites-available/payment.taifaguard.co.ke
```

Update these lines:
```
ssl_certificate /etc/letsencrypt/live/payment.taifaguard.co.ke/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/payment.taifaguard.co.ke/privkey.pem;
```

### 8.4 Enable the site

```bash
sudo ln -s /etc/nginx/sites-available/payment.taifaguard.co.ke /etc/nginx/sites-enabled/
```

### 8.5 Test and reload nginx

```bash
sudo nginx -t
sudo systemctl reload nginx
```

## Step 9: Configure Systemd Service

### 9.1 Copy systemd service file

```bash
sudo cp /var/www/html/internet/payment/payment-service.service /etc/systemd/system/
```

### 9.2 Update paths if needed

```bash
sudo nano /etc/systemd/system/payment-service.service
```

Update the paths if your application is in a different location.

### 9.3 Enable and start the service

```bash
sudo systemctl daemon-reload
sudo systemctl enable payment-service
sudo systemctl start payment-service
```

### 9.4 Check service status

```bash
sudo systemctl status payment-service
```

### 9.5 View logs

```bash
sudo journalctl -u payment-service -f
```

## Step 10: Run Database Migrations

The application will automatically run migrations on startup. You can also run them manually:

```bash
cd /var/www/html/internet/payment
./payment-service migrate
```

## Step 11: Verify Deployment

1. Check nginx is running:
   ```bash
   sudo systemctl status nginx
   ```

2. Check payment service is running:
   ```bash
   sudo systemctl status payment-service
   ```

3. Test the health endpoint:
   ```bash
   curl https://payment.taifaguard.co.ke/health
   ```

4. Test the site:
   - Visit `https://payment.taifaguard.co.ke/health` in your browser
   - Check that SSL certificate is valid
   - Test your API endpoints

## Useful Commands

### Restart Services

```bash
# Restart payment service
sudo systemctl restart payment-service

# Restart nginx
sudo systemctl restart nginx

# Restart both
sudo systemctl restart payment-service nginx
```

### View Logs

```bash
# Payment service logs
sudo journalctl -u payment-service -f

# Nginx logs
sudo tail -f /var/log/nginx/payment.taifaguard.co.ke.error.log
sudo tail -f /var/log/nginx/payment.taifaguard.co.ke.access.log
```

### Update Code

```bash
cd /var/www/html/internet/payment
# Pull latest code or upload new files
go mod tidy  # If dependencies changed
go build -o payment-service .  # Rebuild
sudo systemctl restart payment-service
```

## Security Considerations

1. **Firewall**: Ensure only ports 80 and 443 are open:
   ```bash
   sudo ufw allow 80/tcp
   sudo ufw allow 443/tcp
   sudo ufw enable
   ```

2. **File Permissions**: Ensure proper file ownership:
   ```bash
   sudo chown -R www-data:www-data /var/www/html/internet/payment
   sudo chmod 600 /var/www/html/internet/payment/.env
   ```

3. **Environment Variables**: Never commit `.env` file to version control

## Troubleshooting

### 502 Bad Gateway
- Check if payment service is running: `sudo systemctl status payment-service`
- Check service logs: `sudo journalctl -u payment-service -f`
- Verify the port in nginx config matches the service port (8080)
- Check if the service is listening: `sudo netstat -tlnp | grep 8080`

### Service won't start
- Check logs: `sudo journalctl -u payment-service -n 50`
- Verify `.env` file exists and has correct values
- Check database connection: `psql -U payment_user -d internet -h localhost`
- Check Redis connection: `redis-cli ping`

### SSL certificate issues
- Verify certificate paths in nginx config
- Check certificate expiration: `sudo certbot certificates`
- Renew if needed: `sudo certbot renew`

### Permission denied errors
- Check file ownership: `ls -la /var/www/html/internet/payment`
- Fix ownership: `sudo chown -R www-data:www-data /var/www/html/internet/payment`

### Database connection errors
- Verify PostgreSQL is running: `sudo systemctl status postgresql`
- Test database connection: `psql -U payment_user -d internet -h localhost`
- Check environment variables in `.env` file
- Verify database user has correct permissions


