#!/bin/bash
set -euo pipefail

PROJECT_DIR="/opt/projects/bogazici/corporate-api/test/api"
ENV_SOURCE="/opt/projects/bogazici/corporate-api/test/.env.test"
BRANCH="test"
CONTAINER="bdc-api-test"
COMPOSE_FILE="docker-compose.test.yml"
COMPOSE_PROJECT="bogazici-api-test"
UPLOADS_DIR="/opt/projects/bogazici/corporate-api/test/uploads"

echo "🚀 [API] Test deploy başlatılıyor..."

cd "$PROJECT_DIR"

git config --global --add safe.directory "$PROJECT_DIR" || true

find storage -type d -exec chmod 2775 {} \; 2>/dev/null || true
find storage -type f -exec chmod 664 {} \; 2>/dev/null || true
find bootstrap/cache -type d -exec chmod 2775 {} \; 2>/dev/null || true
find bootstrap/cache -type f -exec chmod 664 {} \; 2>/dev/null || true

git fetch origin
git checkout "$BRANCH"
git reset --hard "origin/$BRANCH"
git clean -fd -e .env

if [ ! -f "$ENV_SOURCE" ]; then
    echo "❌ HATA: env dosyası yok -> $ENV_SOURCE"
    exit 1
fi

cp "$ENV_SOURCE" .env

if ! grep -q '^APP_KEY=base64:' .env; then
    echo "❌ HATA: APP_KEY eksik veya boş -> $ENV_SOURCE"
    exit 1
fi

mkdir -p "$UPLOADS_DIR"
chmod 2775 "$UPLOADS_DIR" 2>/dev/null || true

docker rm -f bogazici-api-test-bdc-api-test-1 2>/dev/null || true
docker rm -f bdc-api-test 2>/dev/null || true

docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" down --remove-orphans || true
docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" up -d --build


echo "⏳ Container hazır olması bekleniyor..."
for i in {1..30}; do
    if docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" ps --status running | grep -q "$CONTAINER"; then
        echo "✅ Container ayakta"
        break
    fi
    if [ "$i" -eq 30 ]; then
        echo "❌ HATA: Container zamanında ayağa kalkmadı"
        docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" logs --tail=100
        exit 1
    fi
    sleep 1
done

docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" exec -T "$CONTAINER" composer install --no-interaction --prefer-dist --optimize-autoloader
docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan optimize:clear
docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan config:cache
docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan route:cache
docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan view:cache

docker image prune -f 2>/dev/null || true

echo "✅ [API] Test deploy tamamlandı"
