#!/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"
UPLOADS_DIR="/opt/projects/bogazici/corporate-api/test/uploads"

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

cd "$PROJECT_DIR"

sudo chown -R "$USER":www-data storage bootstrap/cache 2>/dev/null || true
sudo find storage -type d -exec chmod 2775 {} \; 2>/dev/null || true
sudo find storage -type f -exec chmod 664 {} \; 2>/dev/null || true
sudo find bootstrap/cache -type d -exec chmod 2775 {} \; 2>/dev/null || true
sudo 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

sudo mkdir -p "$UPLOADS_DIR"/{images,videos,hero-slides,settings,pages,courses,announcements,categories}
sudo chown -R "$USER":www-data "$UPLOADS_DIR" 2>/dev/null || true
sudo find "$UPLOADS_DIR" -type d -exec chmod 2775 {} \; 2>/dev/null || true
sudo find "$UPLOADS_DIR" -type f -exec chmod 664 {} \; 2>/dev/null || true

docker stop "$CONTAINER" 2>/dev/null || true
docker rm "$CONTAINER" 2>/dev/null || true
docker compose -f "$COMPOSE_FILE" down --remove-orphans 2>/dev/null || true
docker compose -f "$COMPOSE_FILE" up -d --build

sleep 3
docker compose -f "$COMPOSE_FILE" exec -T "$CONTAINER" composer install --no-interaction --prefer-dist --optimize-autoloader || true
docker compose -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan migrate --force || true
docker compose -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan optimize:clear || true
docker compose -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan config:cache || true
docker compose -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan route:cache || true
docker compose -f "$COMPOSE_FILE" exec -T "$CONTAINER" php artisan view:cache || true

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

echo "✅ [API] Test deploy tamamlandı"
