#!/bin/bash
# Complete AS4 Settlement Setup Script
# Automates all setup steps that can be done without database

set -e

echo "========================================="
echo "AS4 Settlement Complete Setup"
echo "========================================="

cd "$(dirname "$0")/.."

# Step 1: Verify prerequisites
echo ""
echo "Step 1: Verifying prerequisites..."
./scripts/verify-as4-setup.sh || {
    echo "Prerequisites check failed. Please fix errors and try again."
    exit 1
}

# Step 2: Generate certificates
echo ""
echo "Step 2: Generating certificates..."
if [ ! -f "certs/as4/as4-tls-cert.pem" ]; then
    ./scripts/generate-as4-certificates.sh
else
    echo "Certificates already exist, skipping..."
fi

# Step 3: Update .env file
echo ""
echo "Step 3: Updating .env file..."
if [ ! -f ".env" ]; then
    echo "Creating .env from .env.as4.example..."
    cp .env.as4.example .env
    echo "⚠ Please edit .env and configure all values"
else
    echo ".env file exists, checking for AS4 variables..."
    if ! grep -q "AS4_BASE_URL" .env; then
        echo "Adding AS4 variables to .env..."
        cat .env.as4.example >> .env
        echo "⚠ Please review and configure AS4 variables in .env"
    else
        echo "✓ AS4 variables already in .env"
    fi
fi

# Step 4: Install dependencies
echo ""
echo "Step 4: Installing dependencies..."
npm install ajv ajv-formats --save

# Step 5: Generate Prisma client
echo ""
echo "Step 5: Generating Prisma client..."
npx prisma generate

# Step 6: Verify TypeScript compilation
echo ""
echo "Step 6: Verifying TypeScript compilation..."
if npx tsc --noEmit src/core/settlement/as4/**/*.ts src/core/settlement/as4-settlement/**/*.ts 2>&1 | grep -q "error TS"; then
    echo "⚠ TypeScript compilation has errors (may be path resolution issues)"
else
    echo "✓ TypeScript compilation check passed"
fi

# Step 7: Verify routes
echo ""
echo "Step 7: Verifying route registration..."
if grep -q "as4GatewayRoutes" src/integration/api-gateway/app.ts; then
    echo "✓ Routes registered"
else
    echo "✗ Routes not registered"
    exit 1
fi

# Step 8: Create necessary directories
echo ""
echo "Step 8: Creating directories..."
mkdir -p logs/as4
mkdir -p data/as4/vault
mkdir -p certs/as4
echo "✓ Directories created"

# Summary
echo ""
echo "========================================="
echo "Setup Complete!"
echo "========================================="
echo ""
echo "Next steps (require database):"
echo "1. Ensure database is running and accessible"
echo "2. Run migration: npx prisma migrate deploy"
echo "3. Seed marketplace: npx ts-node scripts/seed-as4-settlement-marketplace-offering.ts"
echo "4. Start server: npm run dev"
echo "5. Test endpoints: curl http://localhost:3000/health"
echo ""
