#!/bin/bash
set -euo pipefail

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

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

cd "$PROJECT_DIR"

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

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 compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" down --remove-orphans || true
docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" up -d --build

sleep 5

docker compose -p "$COMPOSE_PROJECT" -f "$COMPOSE_FILE" exec -T "$CONTAINER" composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev
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] Production deploy tamamlandı"
