#!/bin/bash

# Docker build script for Black Canyon Tickets
# Usage: ./scripts/docker-build.sh [version]

set -e

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

# Configuration
IMAGE_NAME="bct-whitelabel"
REGISTRY="${DOCKER_REGISTRY:-}" # Optional registry prefix
VERSION="${1:-latest}"
PLATFORM="${PLATFORM:-linux/amd64}"

echo -e "${GREEN}🐳 Building Docker image for Black Canyon Tickets${NC}"
echo -e "${YELLOW}Image: ${IMAGE_NAME}:${VERSION}${NC}"
echo -e "${YELLOW}Platform: ${PLATFORM}${NC}"

# Build the image
echo -e "${GREEN}📦 Building Docker image...${NC}"
if [ -n "$REGISTRY" ]; then
    FULL_IMAGE_NAME="${REGISTRY}/${IMAGE_NAME}"
else
    FULL_IMAGE_NAME="${IMAGE_NAME}"
fi

docker build \
    --platform "$PLATFORM" \
    --tag "${FULL_IMAGE_NAME}:${VERSION}" \
    --tag "${FULL_IMAGE_NAME}:latest" \
    --build-arg BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
    --build-arg VCS_REF="$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')" \
    --build-arg VERSION="$VERSION" \
    .

echo -e "${GREEN}✅ Docker image built successfully!${NC}"
echo -e "${YELLOW}Image tags:${NC}"
echo -e "  - ${FULL_IMAGE_NAME}:${VERSION}"
echo -e "  - ${FULL_IMAGE_NAME}:latest"

# Optional: Push to registry
if [ "$2" = "--push" ] && [ -n "$REGISTRY" ]; then
    echo -e "${GREEN}🚀 Pushing to registry...${NC}"
    docker push "${FULL_IMAGE_NAME}:${VERSION}"
    docker push "${FULL_IMAGE_NAME}:latest"
    echo -e "${GREEN}✅ Images pushed to registry!${NC}"
fi

# Show image size
echo -e "${GREEN}📊 Image information:${NC}"
docker images "${FULL_IMAGE_NAME}" --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}"

echo -e "${GREEN}🎉 Build complete!${NC}"
echo -e "${YELLOW}To run locally: docker run -p 3000:3000 ${FULL_IMAGE_NAME}:${VERSION}${NC}"
echo -e "${YELLOW}Or use: docker-compose up${NC}"