#!/usr/bin/env bash
# 构建 Docker 镜像脚本

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== 开始构建 PeiPei 后端 Docker 镜像 ===${NC}"

# 检查是否在正确的目录
if [ ! -f "docker/Dockerfile" ]; then
  echo -e "${RED}错误: 请在项目根目录执行此脚本${NC}"
  echo -e "${YELLOW}当前目录: $(pwd)${NC}"
  echo -e "${YELLOW}期望目录应包含: docker/Dockerfile${NC}"
  exit 1
fi

# 获取 UTC+8 时间戳
TIMESTAMP=$(TZ='Asia/Shanghai' date +"%Y-%m-%d-%Hh-%Mm")
echo -e "${YELLOW}构建时间戳 (UTC+8): ${TIMESTAMP}${NC}"

# 镜像名称和标签
IMAGE_NAME="peipei-backend"
VERSION_TAG="${TIMESTAMP}"
LATEST_TAG="latest"

echo -e "${YELLOW}镜像名称: ${IMAGE_NAME}${NC}"
echo -e "${YELLOW}版本标签: ${VERSION_TAG}${NC}"

# 构建 Docker 镜像
echo -e "${GREEN}开始构建镜像...${NC}"
if docker build -f docker/Dockerfile \
  -t "${IMAGE_NAME}:${VERSION_TAG}" \
  -t "${IMAGE_NAME}:${LATEST_TAG}" \
  .; then

  echo -e "${GREEN}✅ Docker 镜像构建成功!${NC}"
  echo -e "${GREEN}镜像标签:${NC}"
  echo -e "  - ${IMAGE_NAME}:${VERSION_TAG}"
  echo -e "  - ${IMAGE_NAME}:${LATEST_TAG}"

  echo -e "\n${YELLOW}镜像信息:${NC}"
  docker images | grep -E "^${IMAGE_NAME}\s" | head -2

  echo -e "\n${GREEN}下一步: 运行 ./push-docker.sh 推送到私有仓库${NC}"
else
  echo -e "${RED}❌ Docker 镜像构建失败!${NC}"
  exit 1
fi
