#!/bin/bash

# Teren App Deployment Script
# This script handles automated deployment from Gitea

set -e  # Exit on any error

echo "🚀 Starting deployment..."

# Configuration
PROJECT_DIR="/var/www/Teren-app"
BRANCH="main"  # Change to your production branch
GITEA_REPO="git@your-gitea-server.com:username/Teren-app.git"

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Change to project directory
cd $PROJECT_DIR

echo "📥 Pulling latest changes from $BRANCH..."
git fetch origin $BRANCH
git reset --hard origin/$BRANCH

echo "🔧 Copying production environment file..."
if [ ! -f .env ]; then
    echo "${RED}❌ .env file not found! Please create it from .env.production.example${NC}"
    exit 1
fi

echo "🐳 Building and starting Docker containers..."
docker-compose down
docker-compose build --no-cache app
docker-compose up -d

echo "⏳ Waiting for containers to be healthy..."
sleep 10

echo "📦 Installing/updating Composer dependencies..."
docker-compose exec -T app composer install --no-dev --optimize-autoloader --no-interaction

echo "🎨 Building frontend assets..."
# If you build assets locally or in CI/CD, uncomment:
# npm ci
# npm run build

echo "🔑 Optimizing Laravel..."
docker-compose exec -T app php artisan config:cache
docker-compose exec -T app php artisan route:cache
docker-compose exec -T app php artisan view:cache
docker-compose exec -T app php artisan event:cache

echo "📊 Running database migrations..."
docker-compose exec -T app php artisan migrate --force

echo "🗄️ Clearing old caches..."
docker-compose exec -T app php artisan cache:clear
docker-compose exec -T app php artisan queue:restart

echo "🔄 Restarting queue workers..."
docker-compose restart app

echo "${GREEN}✅ Deployment completed successfully!${NC}"

# Optional: Send notification (Slack, Discord, etc.)
# curl -X POST -H 'Content-type: application/json' \
#   --data '{"text":"🚀 Teren App deployed successfully!"}' \
#   YOUR_WEBHOOK_URL

# Show running containers
echo "📋 Running containers:"
docker-compose ps
