#!/bin/bash

# 색상 정의
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Content Service 빌드 및 배포 스크립트${NC}"
echo -e "${GREEN}========================================${NC}"

# 1. Gradle 빌드
echo -e "\n${YELLOW}1단계: Gradle 빌드 시작...${NC}"
./gradlew clean content-service:bootJar

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ Gradle 빌드 실패!${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Gradle 빌드 완료${NC}"

# 2. Docker 이미지 빌드
echo -e "\n${YELLOW}2단계: Docker 이미지 빌드 시작...${NC}"
DOCKER_FILE=deployment/container/Dockerfile-backend

docker build \
  --platform linux/amd64 \
  --build-arg BUILD_LIB_DIR="content-service/build/libs" \
  --build-arg ARTIFACTORY_FILE="content-service.jar" \
  -f ${DOCKER_FILE} \
  -t content-service:latest .

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ Docker 이미지 빌드 실패!${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Docker 이미지 빌드 완료${NC}"

# 3. 이미지 확인
echo -e "\n${YELLOW}3단계: 생성된 이미지 확인...${NC}"
docker images | grep content-service

# 4. 기존 컨테이너 중지 및 삭제
echo -e "\n${YELLOW}4단계: 기존 컨테이너 정리...${NC}"
docker-compose -f deployment/container/docker-compose.yml down

# 5. 컨테이너 실행
echo -e "\n${YELLOW}5단계: Content Service 컨테이너 실행...${NC}"
docker-compose -f deployment/container/docker-compose.yml up -d

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 컨테이너 실행 실패!${NC}"
    exit 1
fi

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}✅ 배포 완료!${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "\n${YELLOW}컨테이너 로그 확인:${NC}"
echo -e "  docker logs -f content-service"
echo -e "\n${YELLOW}컨테이너 상태 확인:${NC}"
echo -e "  docker ps"
echo -e "\n${YELLOW}서비스 헬스체크:${NC}"
echo -e "  curl http://localhost:8084/actuator/health"
echo -e "\n${YELLOW}Swagger UI:${NC}"
echo -e "  http://localhost:8084/swagger-ui/index.html"
