#!/bin/bash

echo "🗄️  Initializing AssetX Database..."

# MySQL connection settings
MYSQL_USER="root"
MYSQL_PASSWORD="123456"
MYSQL_HOST="localhost"
MYSQL_PORT="3306"
DB_NAME="assetx"

# Check if MySQL is running
if ! mysqladmin ping -h"$MYSQL_HOST" -P"$MYSQL_PORT" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" --silent 2>/dev/null; then
    echo "❌ MySQL is not running or connection failed"
    echo "   Please start MySQL first: sudo service mysql start"
    exit 1
fi

echo "✓ MySQL is running"

# Create database if not exists
echo "📝 Creating database..."
mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "CREATE DATABASE IF NOT EXISTS $DB_NAME DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null

if [ $? -eq 0 ]; then
    echo "✓ Database '$DB_NAME' created/verified"
else
    echo "❌ Failed to create database"
    exit 1
fi

# Import schema if schema file exists
SCHEMA_FILE="../database-schema-v1.1-final.sql"
if [ -f "$SCHEMA_FILE" ]; then
    echo "📥 Importing database schema..."
    mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SCHEMA_FILE"
    
    if [ $? -eq 0 ]; then
        echo "✓ Schema imported successfully"
    else
        echo "⚠️  Schema import failed (might already exist)"
    fi
else
    echo "⚠️  Schema file not found: $SCHEMA_FILE"
    echo "   Tables will be created by GORM auto-migration"
fi

echo ""
echo "✅ Database initialization complete!"
echo ""
echo "Connection info:"
echo "  Host: $MYSQL_HOST:$MYSQL_PORT"
echo "  Database: $DB_NAME"
echo "  User: $MYSQL_USER"
echo ""
