#!/bin/bash

# Content Service 실행 스크립트
# Port: 8084
# Context Path: /api/v1/content

SERVICE_NAME="content-service"
PORT=8084
LOG_DIR="logs"
LOG_FILE="${LOG_DIR}/${SERVICE_NAME}.log"

# 로그 디렉토리 생성
mkdir -p ${LOG_DIR}

# 환경 변수 설정
export SERVER_PORT=8084
export REDIS_HOST=20.214.210.71
export REDIS_PORT=6379
export REDIS_PASSWORD=Hi5Jessica!
export REDIS_DATABASE=0
export JWT_SECRET=kt-event-marketing-jwt-secret-key-for-authentication-and-authorization-2025
export JWT_ACCESS_TOKEN_VALIDITY=3600000
export JWT_REFRESH_TOKEN_VALIDITY=604800000

# Azure Blob Storage
export AZURE_STORAGE_CONNECTION_STRING="DefaultEndpointsProtocol=https;AccountName=blobkteventstorage;AccountKey=tcBN7mAfojbl0uGsOpU7RNuKNhHnzmwDiWjN31liSMVSrWaEK+HHnYKZrjBXXAC6ZPsuxUDlsf8x+AStd++QYg==;EndpointSuffix=core.windows.net"
export AZURE_CONTAINER_NAME=content-images

# CORS
export CORS_ALLOWED_ORIGINS="http://localhost:8080,http://localhost:8081,http://localhost:8082,http://localhost:8083,http://localhost:8084,http://kt-event-marketing.20.214.196.128.nip.io"
export CORS_ALLOWED_METHODS="GET,POST,PUT,DELETE,OPTIONS,PATCH"
export CORS_ALLOWED_HEADERS="*"
export CORS_ALLOW_CREDENTIALS=true
export CORS_MAX_AGE=3600

# Logging
export LOG_LEVEL_APP=DEBUG
export LOG_LEVEL_WEB=INFO
export LOG_LEVEL_ROOT=INFO
export LOG_FILE_PATH="${LOG_FILE}"
export LOG_FILE_MAX_SIZE=10MB
export LOG_FILE_MAX_HISTORY=7
export LOG_FILE_TOTAL_CAP=100MB

echo "=================================================="
echo "Content Service 시작"
echo "=================================================="
echo "포트: ${PORT}"
echo "로그 파일: ${LOG_FILE}"
echo "Context Path: /api/v1/content"
echo "=================================================="

# 기존 프로세스 확인
if netstat -ano | grep -q ":${PORT}.*LISTENING"; then
    echo "⚠️  포트 ${PORT}가 이미 사용 중입니다."
    echo "기존 프로세스를 종료하시겠습니까? (y/n)"
    read -r answer
    if [ "$answer" = "y" ]; then
        PID=$(netstat -ano | grep ":${PORT}.*LISTENING" | awk '{print $5}' | head -1)
        taskkill //F //PID ${PID}
        sleep 2
    else
        echo "서비스 시작을 취소합니다."
        exit 1
    fi
fi

# 서비스 시작
echo "서비스를 시작합니다..."
nohup ./gradlew ${SERVICE_NAME}:bootRun > ${LOG_FILE} 2>&1 &
SERVICE_PID=$!

echo "✅ Content Service가 시작되었습니다."
echo "PID: ${SERVICE_PID}"
echo "로그 확인: tail -f ${LOG_FILE}"
echo ""
echo "Health Check: curl http://localhost:${PORT}/api/v1/content/actuator/health"
echo ""
echo "서비스 종료: kill ${SERVICE_PID}"
echo "=================================================="
