#!/bin/bash
set -e

# Deploy script for My Weekly To-Do List
# Usage: ./deploy.sh [version]
# Example: ./deploy.sh 1.1.0
#
# Builds the Docker image locally, then restarts the Portainer stack.
# The Portainer stack references "my-weekly-todo:latest".

APP_NAME="my-weekly-todo"
IMAGE_NAME="my-weekly-todo"
PORTAINER_STACK="my-weekly-todo"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}=== $APP_NAME Deploy ===${NC}"

# Ensure we're on main branch
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ]; then
    echo -e "${RED}Error: Must deploy from main branch (currently on '$BRANCH')${NC}"
    echo "Run: git checkout main && git merge dev"
    exit 1
fi

# Check for uncommitted changes
if [ -n "$(git status --porcelain)" ]; then
    echo -e "${RED}Error: Uncommitted changes detected. Commit or stash first.${NC}"
    git status --short
    exit 1
fi

# Optional: bump version
VERSION=$1
if [ -n "$VERSION" ]; then
    echo -e "${YELLOW}Bumping version to $VERSION...${NC}"
    npm version "$VERSION" --no-git-tag-version
    git add package.json package-lock.json
    git commit -m "chore: bump version to v$VERSION"
    git tag -a "v$VERSION" -m "Release v$VERSION"
    echo -e "${GREEN}Tagged v$VERSION${NC}"
fi

CURRENT_VERSION=$(node -p "require('./package.json').version")

# Build Docker image
echo -e "${YELLOW}Building production image ${IMAGE_NAME}:${CURRENT_VERSION}...${NC}"
docker build -t "${IMAGE_NAME}:${CURRENT_VERSION}" -t "${IMAGE_NAME}:latest" .

# Restart the Portainer stack (pull new image)
echo -e "${YELLOW}Restarting Portainer stack...${NC}"
echo -e "${YELLOW}Go to Portainer > Stacks > ${PORTAINER_STACK} > click 'Update the stack' > 'Re-pull image and redeploy'${NC}"
echo ""
echo -e "Or restart via CLI:${NC}"
echo -e "  docker compose -f docker-compose.yml up -d"

echo ""
echo -e "${GREEN}=== Image ${IMAGE_NAME}:${CURRENT_VERSION} ready ===${NC}"
echo -e "${GREEN}=== Also tagged as ${IMAGE_NAME}:latest ===${NC}"
