#!/bin/bash
# scripts/ci/build.sh - Сборка приложения

set -e

echo "🏗️ Building CatLink application..."

# Проверка окружения
echo "📋 Checking environment..."
echo "  • Docker version: $(docker --version)"
echo "  • Docker Compose version: $(docker-compose --version)"
echo "  • Current directory: $(pwd)"
echo "  • Available space: $(df -h . | tail -1 | awk '{print $4}')"

# Создание .env файла для CI если не существует
if [ ! -f ".env" ]; then
    echo "⚙️ Creating .env file for CI..."
    cp .env.example .env
    
    # Установка переменных для CI
    cat >> .env << EOF

# CI/CD Variables
CI=true
NODE_ENV=test
DJANGO_ENV=test
DEBUG=False
DATABASE_URL=postgres://catlink:catlink@postgres:5432/catlink_test
SECRET_KEY=ci-secret-key-for-testing-only
ALLOWED_HOSTS=localhost,127.0.0.1,testserver
EOF
fi

# Очистка предыдущих сборок
echo "🧹 Cleaning up previous builds..."
docker-compose down --remove-orphans || true
docker system prune -f || true

# Сборка образов
echo "🔨 Building Docker images..."
echo "  • Building backend image..."
docker-compose build web --no-cache

echo "  • Building frontend image..."
docker-compose build frontend --no-cache

# Проверка размера образов
echo "📊 Checking image sizes..."
docker images | grep -E "(catlink|links)" | head -10

# Запуск контейнеров для проверки
echo "🚀 Starting containers for verification..."
docker-compose up -d

# Ожидание готовности сервисов
echo "⏳ Waiting for services to be ready..."
sleep 30

# Проверка статуса контейнеров
echo "🔍 Checking container status..."
docker-compose ps

# Проверка логов на ошибки
echo "📋 Checking logs for errors..."
docker-compose logs web | tail -20
docker-compose logs frontend | tail -20

# Проверка здоровья сервисов
echo "🏥 Health check..."
backend_health=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/api/ || echo "000")
frontend_health=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000 || echo "000")

echo "  • Backend API health: $backend_health"
echo "  • Frontend health: $frontend_health"

if [ "$backend_health" = "200" ] && [ "$frontend_health" = "200" ]; then
    echo "✅ Build completed successfully!"
    echo "  • Backend: http://localhost:8000"
    echo "  • Frontend: http://localhost:3000"
else
    echo "❌ Build failed - services not responding properly"
    echo "Backend logs:"
    docker-compose logs web | tail -50
    echo "Frontend logs:"
    docker-compose logs frontend | tail -50
    exit 1
fi

# Экспорт образов для последующих этапов
echo "💾 Exporting images for next stages..."
docker save -o /tmp/catlink-images.tar $(docker images --format "{{.Repository}}:{{.Tag}}" | grep -E "(catlink|links)")

echo "🎉 Build stage completed successfully!"