#!/bin/bash

# Database seeding script for Magasinet KBH
# This script seeds the database with initial data for development
# Works with both Docker and local database setups

set -e  # Exit on any error

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

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

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

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to check if Docker is running
check_docker() {
    if ! docker info &> /dev/null; then
        print_error "Docker daemon is not running. Please start Docker first."
        exit 1
    fi
}

# Function to check if database is accessible
check_database_connection() {
    local db_url=$1
    local max_attempts=30
    local attempt=1
    
    print_status "Checking database connection..."
    
    while [ $attempt -le $max_attempts ]; do
        local postgres_container=$(docker ps --filter "name=postgres" --format "{{.Names}}" | head -1)
        if [ -n "$postgres_container" ] && docker exec "$postgres_container" pg_isready -U postgres -d magasinetkbh &> /dev/null; then
            print_success "Database is ready!"
            return 0
        fi
        
        print_status "Waiting for database... (attempt $attempt/$max_attempts)"
        sleep 2
        ((attempt++))
    done
    
    print_error "Database is not accessible after $max_attempts attempts"
    return 1
}

# Function to run migrations
run_migrations() {
    print_status "Running database migrations..."
    
    if command_exists pnpm; then
        pnpm db:migrate
    elif command_exists npm; then
        npm run db:migrate
    else
        print_error "Neither pnpm nor npm found. Please install one of them."
        exit 1
    fi
    
    print_success "Migrations completed successfully"
}

# Function to seed the database
seed_database() {
    print_status "Seeding database with initial data..."
    
    if command_exists pnpm; then
        pnpm db:seed
    elif command_exists npm; then
        npm run db:seed
    else
        print_error "Neither pnpm nor npm found. Please install one of them."
        exit 1
    fi
    
    print_success "Database seeding completed successfully"
}

# Function to check if Docker containers are running
check_docker_containers() {
    local postgres_container=$(docker ps --filter "name=postgres" --format "{{.Names}}" | head -1)
    
    if [ -z "$postgres_container" ]; then
        print_warning "PostgreSQL container not found. Checking if database is running locally..."
        return 1
    fi
    
    print_status "Found PostgreSQL container: $postgres_container"
    return 0
}

# Function to check if database is running locally
check_local_database() {
    if command_exists psql; then
        # Try to connect to local database
        if psql -h localhost -p 5432 -U postgres -d magasinetkbh -c "SELECT 1;" &> /dev/null; then
            print_status "Found local PostgreSQL database"
            return 0
        fi
    fi
    
    return 1
}

# Main function
main() {
    echo "🌱 Magasinet KBH Database Seeding Script"
    echo "========================================"
    echo ""
    
    # Check if we're in the right directory
    if [ ! -f "package.json" ] || [ ! -f "src/lib/database/seed.ts" ]; then
        print_error "Please run this script from the project root directory"
        exit 1
    fi
    
    # Check if .env.local exists
    if [ ! -f ".env.local" ]; then
        print_error ".env.local file not found!"
        echo "Please run './infrastructure/setup_docker.sh' first to set up the environment."
        exit 1
    fi
    
    # Load environment variables
    print_status "Loading environment variables from .env.local..."
    set -a  # automatically export all variables
    source .env.local
    set +a  # stop automatically exporting
    
    # Determine database setup
    if check_docker_containers; then
        print_status "Using Docker database setup"
        check_docker
        check_database_connection "$DATABASE_URL_DOCKER"
    elif check_local_database; then
        print_status "Using local database setup"
    else
        print_error "No accessible database found!"
        echo ""
        echo "Please ensure one of the following is running:"
        echo "  1. Docker containers: ./infrastructure/start_docker.sh"
        echo "  2. Local PostgreSQL database"
        echo ""
        exit 1
    fi
    
    # Run migrations
    run_migrations
    
    # Seed the database
    seed_database
    
    echo ""
    print_success "🎉 Database seeding completed successfully!"
    echo ""
    echo "📊 What was seeded:"
    echo "  - 3 users (admin, editor, regular user)"
    echo "  - 50 sample posts with various topics"
    echo "  - Tags and post-tag associations"
    echo "  - Random comments and replies"
    echo "  - Random reactions (likes/dislikes)"
    echo "  - All posts include the new sharesCount field"
    echo ""
    echo "🔑 Test accounts:"
    echo "  - Admin: admin@example.com / AdminPass123!"
    echo "  - Editor: editor@example.com / EditorPass123!"
    echo "  - User: user@example.com / UserPass123!"
    echo ""
    echo "🌐 Access your application:"
    echo "  - Application: http://localhost:3000"
    echo "  - Mailpit (Email Testing): http://localhost:8025"
    echo "  - MinIO Console: http://localhost:9001"
    echo ""
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --help, -h      Show this help message"
            echo ""
            echo "This script seeds the database with initial data for development."
            echo "It works with both Docker and local database setups."
            echo ""
            echo "Prerequisites:"
            echo "  - .env.local file (created by setup_docker.sh)"
            echo "  - Database running (Docker or local)"
            echo "  - pnpm or npm installed"
            echo ""
            echo "Examples:"
            echo "  $0                    # Seed the database"
            echo "  $0 --help            # Show this help"
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            echo "Use --help for usage information."
            exit 1
            ;;
    esac
done

# Run main function
main
