#!/bin/bash
# Run Chart of Accounts Migration and Initialization

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

cd "$PROJECT_ROOT"

echo "=========================================="
echo "Chart of Accounts Migration & Setup"
echo "=========================================="
echo ""

# Check if DATABASE_URL is set
if [ -z "$DATABASE_URL" ]; then
    echo "⚠️  DATABASE_URL not set. Checking for .env file..."
    if [ -f .env ]; then
        echo "✅ Found .env file, loading environment variables..."
        export $(cat .env | grep -v '^#' | xargs)
    else
        echo "❌ Error: DATABASE_URL not set and no .env file found."
        echo ""
        echo "Please set DATABASE_URL or create a .env file with:"
        echo "  DATABASE_URL=postgresql://user:password@host:port/database"
        echo ""
        exit 1
    fi
fi

# Source nvm if available (for Node.js environment)
if [ -f "$HOME/.nvm/nvm.sh" ]; then
    source "$HOME/.nvm/nvm.sh" 2>/dev/null || true
elif [ -f "/root/.nvm/nvm.sh" ]; then
    source "/root/.nvm/nvm.sh" 2>/dev/null || true
fi

# Use local prisma if available, otherwise try npx
PRISMA_CMD=""
if [ -f "./node_modules/.bin/prisma" ]; then
    PRISMA_CMD="./node_modules/.bin/prisma"
elif command -v npx &> /dev/null; then
    PRISMA_CMD="npx prisma"
else
    echo "❌ Error: Prisma not found. Please install dependencies with 'npm install'"
    exit 1
fi

echo "Step 1: Generating Prisma client..."
$PRISMA_CMD generate

echo ""
echo "Step 2: Creating migration..."
$PRISMA_CMD migrate dev --name add_chart_of_accounts

echo ""
echo "Step 3: Initializing Chart of Accounts..."

# Try to use ts-node from node_modules first
if [ -f "./node_modules/.bin/ts-node" ]; then
    ./node_modules/.bin/ts-node scripts/initialize-chart-of-accounts.ts
elif command -v ts-node &> /dev/null; then
    ts-node scripts/initialize-chart-of-accounts.ts
elif [ -f "dist/scripts/initialize-chart-of-accounts.js" ]; then
    node dist/scripts/initialize-chart-of-accounts.js
else
    echo "⚠️  TypeScript not compiled. Building first..."
    if [ -f "./node_modules/.bin/npm" ]; then
        ./node_modules/.bin/npm run build
    elif command -v npm &> /dev/null; then
        npm run build
    else
        echo "❌ Error: npm not found. Cannot build TypeScript."
        exit 1
    fi
    node dist/scripts/initialize-chart-of-accounts.js
fi

echo ""
echo "=========================================="
echo "✅ Chart of Accounts setup complete!"
echo "=========================================="
