#!/bin/bash
# ==============================================================================
# RDM RSP API - Docker Build Script
# ==============================================================================
# Builds the Docker image with proper tagging and caching
#
# Usage:
#   ./build-docker.sh              # Build with default tag (latest)
#   ./build-docker.sh v1.0.0       # Build with specific version tag
#   ./build-docker.sh --no-cache   # Build without cache
# ==============================================================================

set -e  # Exit on any error

# ==============================================================================
# Configuration
# ==============================================================================
IMAGE_NAME="rdm-rsp-api"
REGISTRY=""  # Add your registry here, e.g., "docker.io/myorg/" or "ghcr.io/org/"
VERSION="${1:-latest}"
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")

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

# ==============================================================================
# Functions
# ==============================================================================

print_header() {
    echo -e "${BLUE}"
    echo "=============================================================================="
    echo " RDM RSP API - Docker Build"
    echo "=============================================================================="
    echo -e "${NC}"
}

print_step() {
    echo -e "${GREEN}[STEP]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker is not installed or not in PATH"
        exit 1
    fi

    if ! docker info &> /dev/null; then
        print_error "Docker daemon is not running"
        exit 1
    fi
}

# ==============================================================================
# Pre-flight Checks
# ==============================================================================

print_header

print_step "Running pre-flight checks..."

# Check Docker
check_docker

# Check if Dockerfile exists
if [[ ! -f "Dockerfile" ]]; then
    print_error "Dockerfile not found in current directory"
    exit 1
fi

# Check if we're in the right directory
if [[ ! -f "RspApi.csproj" ]]; then
    print_error "Not in the project root directory (RspApi.csproj not found)"
    exit 1
fi

print_info "All pre-flight checks passed"

# ==============================================================================
# Build Configuration
# ==============================================================================

echo ""
print_step "Build Configuration:"
echo "  Image Name:    ${IMAGE_NAME}"
echo "  Version:       ${VERSION}"
echo "  Registry:      ${REGISTRY:-"(local)"}"
echo "  Git Commit:    ${GIT_COMMIT}"
echo "  Build Date:    ${BUILD_DATE}"
echo ""

# Parse arguments
NO_CACHE=""
PUSH_IMAGE=false

for arg in "$@"; do
    case $arg in
        --no-cache)
            NO_CACHE="--no-cache"
            print_info "Building without cache"
            ;;
        --push)
            PUSH_IMAGE=true
            print_info "Will push image after build"
            ;;
    esac
done

# ==============================================================================
# Build Image
# ==============================================================================

print_step "Building Docker image..."

FULL_IMAGE_NAME="${REGISTRY}${IMAGE_NAME}"

# Build with multiple tags
docker build \
    ${NO_CACHE} \
    --tag "${FULL_IMAGE_NAME}:${VERSION}" \
    --tag "${FULL_IMAGE_NAME}:latest" \
    --label "org.opencontainers.image.created=${BUILD_DATE}" \
    --label "org.opencontainers.image.revision=${GIT_COMMIT}" \
    --label "org.opencontainers.image.version=${VERSION}" \
    --label "org.opencontainers.image.title=RDM RSP API" \
    --label "org.opencontainers.image.description=RDM RSP Web API for taxpayer services" \
    --progress=plain \
    .

BUILD_STATUS=$?

if [[ $BUILD_STATUS -ne 0 ]]; then
    print_error "Docker build failed with exit code ${BUILD_STATUS}"
    exit $BUILD_STATUS
fi

echo ""
print_step "Build completed successfully!"

# ==============================================================================
# Show Image Info
# ==============================================================================

echo ""
print_step "Image Information:"
docker images "${FULL_IMAGE_NAME}" --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}"

# ==============================================================================
# Push Image (if requested)
# ==============================================================================

if [[ "$PUSH_IMAGE" == true ]]; then
    if [[ -z "$REGISTRY" ]]; then
        print_warning "No registry configured, skipping push"
    else
        print_step "Pushing image to registry..."
        docker push "${FULL_IMAGE_NAME}:${VERSION}"
        docker push "${FULL_IMAGE_NAME}:latest"
        print_info "Image pushed successfully"
    fi
fi

# ==============================================================================
# Security Scan (optional)
# ==============================================================================

if command -v docker &> /dev/null && docker scout version &> /dev/null; then
    echo ""
    print_step "Running security scan with Docker Scout..."
    docker scout quickview "${FULL_IMAGE_NAME}:${VERSION}" || true
fi

# ==============================================================================
# Summary
# ==============================================================================

echo ""
echo -e "${GREEN}=============================================================================="
echo " BUILD SUCCESSFUL"
echo "==============================================================================${NC}"
echo ""
echo "To run the container locally:"
echo "  docker run -p 8080:8080 --env-file .env ${FULL_IMAGE_NAME}:${VERSION}"
echo ""
echo "Or use docker-compose:"
echo "  cp .env.example .env"
echo "  # Edit .env with your values"
echo "  docker-compose up -d"
echo ""
echo "To test the API:"
echo "  curl http://localhost:8080/swagger/index.html"
echo ""
