#!/bin/bash
# Complete Chart of Accounts Setup
# This script attempts to:
# 1. Grant database permissions (if on Proxmox host)
# 2. Run migration
# 3. Initialize accounts
# 4. Verify setup

set -e

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

cd "$PROJECT_ROOT"

echo "=========================================="
echo "Complete Chart of Accounts Setup"
echo "=========================================="
echo ""

# Configuration
VMID="${VMID:-10100}"
DB_HOST="${DB_HOST:-192.168.11.105}"
DB_NAME="${DB_NAME:-dbis_core}"
DB_USER="${DB_USER:-dbis}"

# Step 1: Grant Database Permissions
echo "Step 1: Granting Database Permissions..."
echo ""

if command -v pct &> /dev/null; then
    echo "✅ Running on Proxmox host - granting permissions..."
    "$SCRIPT_DIR/grant-database-permissions.sh"
    PERMISSIONS_GRANTED=$?
else
    echo "⚠️  Not on Proxmox host - skipping permission grant"
    echo "   Permissions must be granted manually on Proxmox host:"
    echo "   ssh root@192.168.11.10"
    echo "   cd /root/proxmox/dbis_core"
    echo "   ./scripts/grant-database-permissions.sh"
    echo ""
    read -p "Have permissions been granted? (y/n): " PERMISSIONS_GRANTED_INPUT
    if [[ "$PERMISSIONS_GRANTED_INPUT" == "y" || "$PERMISSIONS_GRANTED_INPUT" == "Y" ]]; then
        PERMISSIONS_GRANTED=0
    else
        echo "❌ Please grant permissions first, then run this script again"
        exit 1
    fi
fi

if [ $PERMISSIONS_GRANTED -ne 0 ]; then
    echo "❌ Failed to grant permissions"
    exit 1
fi

echo ""
echo "Step 2: Running Migration..."
echo ""

# Run the migration script
"$SCRIPT_DIR/run-chart-of-accounts-migration.sh"

MIGRATION_STATUS=$?

if [ $MIGRATION_STATUS -ne 0 ]; then
    echo "❌ Migration failed"
    exit 1
fi

echo ""
echo "Step 3: Verifying Setup..."
echo ""

# Check if DATABASE_URL is available
if [ -z "$DATABASE_URL" ]; then
    if [ -f .env ]; then
        export $(cat .env | grep -v '^#' | xargs)
    fi
fi

# Verify accounts were created
if command -v psql &> /dev/null && [ -n "$DATABASE_URL" ]; then
    echo "Checking account count..."
    ACCOUNT_COUNT=$(psql "$DATABASE_URL" -t -c "SELECT COUNT(*) FROM chart_of_accounts;" 2>/dev/null | xargs)
    
    if [ -n "$ACCOUNT_COUNT" ] && [ "$ACCOUNT_COUNT" -gt 0 ]; then
        echo "✅ Found $ACCOUNT_COUNT accounts in database"
        
        # Show summary by category
        echo ""
        echo "Account Summary:"
        psql "$DATABASE_URL" -c "
        SELECT 
            category,
            COUNT(*) as count
        FROM chart_of_accounts
        WHERE is_active = true
        GROUP BY category
        ORDER BY category;
        " 2>/dev/null || true
    else
        echo "⚠️  Could not verify account count (this is okay if psql is not available)"
    fi
else
    echo "⚠️  psql not available or DATABASE_URL not set - skipping verification"
    echo "   You can verify manually:"
    echo "   psql \"$DATABASE_URL\" -c \"SELECT COUNT(*) FROM chart_of_accounts;\""
fi

echo ""
echo "=========================================="
echo "✅ Chart of Accounts Setup Complete!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Test API endpoints:"
echo "   curl http://localhost:3000/api/accounting/chart-of-accounts"
echo ""
echo "2. View accounts by category:"
echo "   curl http://localhost:3000/api/accounting/chart-of-accounts/category/ASSET"
echo ""
