#!/bin/bash

# ──────────────────────────────────────────────────────
# BerryFoods Database Import Script
# ──────────────────────────────────────────────────────
# Imports a SQL file into the WordPress database
#
# Usage: ./scripts/db-import.sh <input_filename.sql>
#
# Examples:
#   ./scripts/db-import.sh berryfoods_db.sql
#   ./scripts/db-import.sh berryfoods_db.sql.gz   # Auto-detects gzip
# ──────────────────────────────────────────────────────

set -e

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

# Configuration
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${PROJECT_ROOT}/.env"

# Load environment variables
if [ -f "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | xargs -d '\n' 2>/dev/null || grep -v '^#' "$ENV_FILE" | xargs)
fi

# Database configuration
DB_HOST="${DB_HOST:-localhost}"
DB_NAME="${MYSQL_DATABASE:-wordpress}"
DB_USER="${MYSQL_USER:-wordpress}"
DB_PASS="${MYSQL_PASSWORD:-wordpress_password_2024}"

# Docker container name
DOCKER_CONTAINER="${DOCKER_CONTAINER:-berry_whole_foods-wordpress_db-1}"

echo -e "${BLUE}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║       BerryFoods Database Import Script               ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════╝${NC}"
echo ""

# Check for input file
INPUT_FILE="$1"

if [ -z "$INPUT_FILE" ]; then
    # Look for default file
    if [ -f "${PROJECT_ROOT}/berryfoods_db.sql.gz" ]; then
        INPUT_FILE="${PROJECT_ROOT}/berryfoods_db.sql.gz"
    elif [ -f "${PROJECT_ROOT}/berryfoods_db.sql" ]; then
        INPUT_FILE="${PROJECT_ROOT}/berryfoods_db.sql"
    else
        echo -e "${RED}✗ No input file specified and no default file found.${NC}"
        echo ""
        echo -e "${YELLOW}Usage: ./scripts/db-import.sh <filename.sql>${NC}"
        echo ""
        exit 1
    fi
fi

if [ ! -f "$INPUT_FILE" ]; then
    echo -e "${RED}✗ File not found: ${INPUT_FILE}${NC}"
    exit 1
fi

echo -e "${GREEN}Input file: ${INPUT_FILE}${NC}"
echo -e "${GREEN}Database:   ${DB_NAME}${NC}"
echo ""

# Check if compressed
IS_COMPRESSED=false
if [[ "$INPUT_FILE" == *.gz ]]; then
    IS_COMPRESSED=true
fi

# Function to check if Docker is available
check_docker() {
    if command -v docker &> /dev/null; then
        if docker ps --format '{{.Names}}' | grep -q "$DOCKER_CONTAINER"; then
            return 0
        fi
    fi
    return 1
}

# Function to import using Docker
import_via_docker() {
    echo -e "${YELLOW}→ Using Docker container: ${DOCKER_CONTAINER}${NC}"
    
    if [ "$IS_COMPRESSED" = true ]; then
        echo -e "${YELLOW}→ Decompressing and importing...${NC}"
        gunzip -c "$INPUT_FILE" | docker exec -i "$DOCKER_CONTAINER" mysql \
            -u"$DB_USER" \
            -p"$DB_PASS" \
            "$DB_NAME"
    else
        echo -e "${YELLOW}→ Importing SQL file...${NC}"
        docker exec -i "$DOCKER_CONTAINER" mysql \
            -u"$DB_USER" \
            -p"$DB_PASS" \
            "$DB_NAME" < "$INPUT_FILE"
    fi
}

# Function to import using local mysql
import_via_local() {
    echo -e "${YELLOW}→ Using local mysql client${NC}"
    
    if ! command -v mysql &> /dev/null; then
        echo -e "${RED}✗ mysql client not found. Please install MySQL client tools.${NC}"
        echo -e "${YELLOW}  Ubuntu/Debian: sudo apt-get install mysql-client${NC}"
        echo -e "${YELLOW}  macOS: brew install mysql${NC}"
        exit 1
    fi
    
    if [ "$IS_COMPRESSED" = true ]; then
        echo -e "${YELLOW}→ Decompressing and importing...${NC}"
        gunzip -c "$INPUT_FILE" | mysql \
            -h"$DB_HOST" \
            -u"$DB_USER" \
            -p"$DB_PASS" \
            "$DB_NAME"
    else
        echo -e "${YELLOW}→ Importing SQL file...${NC}"
        mysql \
            -h"$DB_HOST" \
            -u"$DB_USER" \
            -p"$DB_PASS" \
            "$DB_NAME" < "$INPUT_FILE"
    fi
}

# Warning and confirmation
echo -e "${RED}⚠ WARNING: This will OVERWRITE the current database!${NC}"
echo ""
read -p "Are you sure you want to continue? (y/N): " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Import cancelled.${NC}"
    exit 0
fi

# Main import logic
if check_docker; then
    import_via_docker
else
    echo -e "${YELLOW}→ Docker container not found, attempting local connection...${NC}"
    import_via_local
fi

echo ""
echo -e "${GREEN}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║                  Import Successful!                    ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${GREEN}Database '${DB_NAME}' has been updated.${NC}"
echo ""
echo -e "${YELLOW}Note: You may need to clear your browser cache and WordPress${NC}"
echo -e "${YELLOW}object cache if you experience any issues.${NC}"
echo ""
