#!/bin/bash

echo "🚀 Setting up Nordic Storium Development Environment"
echo "=================================================="

# Check for required files
if [ ! -f .env ]; then
    echo "Creating .env file from .env.example..."
    cp .env.example .env
    echo "⚠️  Please edit .env file with your actual values!"
    echo "   Important: Change all passwords and secret keys!"
    exit 1
fi

if [ ! -f .env.local ]; then
    echo "Creating .env.local file..."
    cp .env .env.local
    echo "✅ Created .env.local (you can override settings here)"
fi

# Check Docker
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first."
    exit 1
fi

if ! command -v docker compose &> /dev/null; then
    echo "❌ Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi

# Load environment variables
echo "Loading environment variables..."
set -a
source .env
set +a

# Create required directories
echo "Creating required directories..."
mkdir -p schemas config

# Create phpMyAdmin config if it doesn't exist
if [ ! -f config/user.config.inc.php ]; then
    echo "Creating phpMyAdmin configuration..."
    cat > config/user.config.inc.php << 'EOF'
<?php
/* phpMyAdmin configuration for Nordic Storium */
$cfg['Servers'][1]['auth_type'] = 'cookie';
$cfg['LoginCookieRecall'] = false;
$cfg['LoginCookieStore'] = 0;
$cfg['AllowArbitraryServer'] = false;
$cfg['Servers'][1]['AllowNoPassword'] = false;
$cfg['Servers'][1]['AllowRoot'] = true;
$cfg['ForceSSL'] = false;
EOF
fi

# Create database schema if it doesn't exist
if [ ! -f schemas/init.sql ]; then
    echo "Creating database schema..."
    cat > schemas/init.sql << 'EOF'
-- Nordic Storium Database Initialization
USE nordic_storium;

-- Create users table
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    username VARCHAR(50) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    full_name VARCHAR(100),
    role ENUM('user', 'admin', 'moderator') DEFAULT 'user',
    is_active BOOLEAN DEFAULT TRUE,
    email_verified BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_email (email),
    INDEX idx_username (username)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
EOF
fi

# Build and start containers
echo "Building Docker images..."
docker compose build --no-cache

echo "Starting services..."
docker compose up -d

echo "Waiting for database to be ready..."
sleep 15

# Test database connection
echo "Testing database connection..."
for i in {1..10}; do
    if docker exec nordicstorium-db mysqladmin ping -h localhost -u root -p${ROOT_DB_PASSWORD} --silent; then
        echo "✅ Database is ready!"
        break
    fi
    echo "⏳ Waiting for database... ($i/10)"
    sleep 5
done

echo ""
echo "=================================================="
echo "✅ Setup Complete!"
echo ""
echo "📱 Your application is running at:"
echo "   🌐 Website: http://localhost:3000"
echo "   🗄️  Database Admin: http://localhost:8081"
echo ""
echo "🔐 Login credentials:"
echo "   phpMyAdmin (root): root / ${ROOT_DB_PASSWORD}"
echo "   phpMyAdmin (app): nordic_app_user / ${APP_DB_PASSWORD}"
echo ""
echo "📊 Test database connection:"
echo "   curl http://localhost:3000/api/db-test"
echo ""
echo "🛑 To stop everything: docker compose down"
echo "📝 To view logs: docker compose logs -f"
echo "=================================================="