#!/bin/bash

# Enamel Wallet - Complete Setup Script
# This script sets up the entire development environment from scratch

set -e  # Exit on error

echo "🚀 Enamel Wallet - Complete Setup"
echo "=================================="
echo ""

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

# Step 1: Check prerequisites
echo -e "${BLUE}Step 1: Checking prerequisites...${NC}"
echo ""

# Check Node.js
if command -v node &> /dev/null; then
    NODE_VERSION=$(node -v)
    echo -e "${GREEN}✓${NC} Node.js installed: $NODE_VERSION"
else
    echo -e "${RED}✗${NC} Node.js not found"
    echo "Please install Node.js 18+ from https://nodejs.org/"
    exit 1
fi

# Check npm
if command -v npm &> /dev/null; then
    NPM_VERSION=$(npm -v)
    echo -e "${GREEN}✓${NC} npm installed: $NPM_VERSION"
else
    echo -e "${RED}✗${NC} npm not found"
    exit 1
fi

# Check PostgreSQL
if command -v psql &> /dev/null; then
    PSQL_VERSION=$(psql --version | awk '{print $3}')
    echo -e "${GREEN}✓${NC} PostgreSQL installed: $PSQL_VERSION"
else
    echo -e "${YELLOW}⚠${NC} PostgreSQL not found"
    echo "Please install PostgreSQL 14+ from https://www.postgresql.org/download/"
    echo ""
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo ""

# Step 2: Environment files
echo -e "${BLUE}Step 2: Setting up environment files...${NC}"
echo ""

if [ ! -f ".env" ]; then
    echo "Creating frontend .env file..."
    cp env.example .env 2>/dev/null || cat > .env << 'EOF'
VITE_API_URL=http://localhost:5000/api
VITE_APP_NAME=Enamel Wallet
VITE_APP_ENV=development
VITE_TEST_MODE=true
VITE_MOCK_API=false
VITE_DEBUG_MODE=true
EOF
    echo -e "${GREEN}✓${NC} Created .env"
else
    echo -e "${GREEN}✓${NC} .env already exists"
fi

if [ ! -f "backend/.env" ]; then
    echo "Creating backend .env file..."
    cp backend/.env.example backend/.env 2>/dev/null || cat > backend/.env << 'EOF'
NODE_ENV=development
PORT=5000
DB_HOST=localhost
DB_PORT=5432
DB_NAME=enamel_wallet
DB_USER=postgres
DB_PASSWORD=postgres
JWT_SECRET=enamel-wallet-super-secure-jwt-secret-development-only-change-in-production
JWT_REFRESH_SECRET=enamel-wallet-super-secure-refresh-secret-development-only-change-in-production
JWT_EXPIRATION=24h
JWT_REFRESH_EXPIRATION=7d
PAYSTACK_SECRET_KEY=sk_test_your-paystack-secret-key
PREMBLY_API_KEY=your-prembly-api-key
PREMBLY_APP_ID=your-prembly-app-id
CORS_ORIGIN=http://localhost:5173
TEST_MODE=true
LOG_LEVEL=info
EOF
    echo -e "${GREEN}✓${NC} Created backend/.env"
    echo -e "${YELLOW}⚠${NC} Remember to update database credentials and API keys!"
else
    echo -e "${GREEN}✓${NC} backend/.env already exists"
fi

echo ""

# Step 3: Install dependencies
echo -e "${BLUE}Step 3: Installing dependencies...${NC}"
echo ""

echo "Installing frontend dependencies..."
npm install
echo -e "${GREEN}✓${NC} Frontend dependencies installed"

echo ""
echo "Installing backend dependencies..."
cd backend
npm install
cd ..
echo -e "${GREEN}✓${NC} Backend dependencies installed"

echo ""

# Step 4: Database setup
echo -e "${BLUE}Step 4: Setting up database...${NC}"
echo ""

if command -v psql &> /dev/null; then
    # Get database name from .env
    DB_NAME=$(grep "^DB_NAME=" backend/.env | cut -d'=' -f2)
    DB_NAME=${DB_NAME:-enamel_wallet}
    
    echo "Checking if database exists..."
    if psql -lqt 2>/dev/null | cut -d \| -f 1 | grep -qw "$DB_NAME"; then
        echo -e "${GREEN}✓${NC} Database '$DB_NAME' already exists"
    else
        echo "Creating database '$DB_NAME'..."
        createdb "$DB_NAME" 2>/dev/null && echo -e "${GREEN}✓${NC} Database created" || {
            echo -e "${YELLOW}⚠${NC} Could not create database automatically"
            echo "Please create it manually: createdb $DB_NAME"
        }
    fi
    
    # Load schema
    echo "Loading database schema..."
    if [ -f "DATABASE_SCHEMA.sql" ]; then
        psql -d "$DB_NAME" -f DATABASE_SCHEMA.sql > /dev/null 2>&1 && \
            echo -e "${GREEN}✓${NC} Schema loaded from DATABASE_SCHEMA.sql" || \
            echo -e "${YELLOW}⚠${NC} Could not load schema (may already exist)"
    elif [ -f "backend/src/database/schema.sql" ]; then
        psql -d "$DB_NAME" -f backend/src/database/schema.sql > /dev/null 2>&1 && \
            echo -e "${GREEN}✓${NC} Schema loaded from backend/src/database/schema.sql" || \
            echo -e "${YELLOW}⚠${NC} Could not load schema (may already exist)"
    else
        echo -e "${YELLOW}⚠${NC} Schema file not found"
    fi
else
    echo -e "${YELLOW}⚠${NC} PostgreSQL not available, skipping database setup"
    echo "You'll need to set up the database manually"
fi

echo ""

# Step 5: Make scripts executable
echo -e "${BLUE}Step 5: Setting up helper scripts...${NC}"
echo ""

chmod +x start-dev.sh 2>/dev/null && echo -e "${GREEN}✓${NC} start-dev.sh is executable"
chmod +x check-env.sh 2>/dev/null && echo -e "${GREEN}✓${NC} check-env.sh is executable"
chmod +x setup-complete.sh 2>/dev/null && echo -e "${GREEN}✓${NC} setup-complete.sh is executable"

echo ""

# Step 6: Run environment check
echo -e "${BLUE}Step 6: Running environment validation...${NC}"
echo ""

if [ -f "./check-env.sh" ]; then
    ./check-env.sh
else
    echo -e "${YELLOW}⚠${NC} check-env.sh not found, skipping validation"
fi

echo ""

# Summary
echo "=================================="
echo -e "${GREEN}✓ Setup Complete!${NC}"
echo "=================================="
echo ""
echo "Your Enamel Wallet development environment is ready!"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo ""
echo "1. Update API keys in backend/.env:"
echo "   - PAYSTACK_SECRET_KEY (get from https://dashboard.paystack.com)"
echo "   - PREMBLY_API_KEY (get from https://prembly.com/developers)"
echo ""
echo "2. Update database credentials in backend/.env if needed:"
echo "   - DB_USER"
echo "   - DB_PASSWORD"
echo ""
echo "3. Start development servers:"
echo "   ${GREEN}./start-dev.sh${NC}"
echo ""
echo "4. Open your browser to:"
echo "   ${GREEN}http://localhost:5173${NC}"
echo ""
echo -e "${BLUE}Documentation:${NC}"
echo "   - START_HERE.md - Quick start guide"
echo "   - ENV_FIX_README.md - Environment fix details"
echo "   - QUICK_FIX_GUIDE.md - Troubleshooting"
echo ""
echo "Happy coding! 🚀"
echo ""
