#!/bin/bash
# AS4 Settlement Deployment Script

set -e

echo "========================================="
echo "AS4 Settlement Deployment Script"
echo "========================================="

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

# Step 1: Generate Prisma Client
echo ""
echo "Step 1: Generating Prisma Client..."
npx prisma generate

# Step 2: Run Database Migration
echo ""
echo "Step 2: Running database migration..."
if npx prisma migrate deploy; then
    echo "✓ Migration successful"
else
    echo "⚠ Migration failed - database may not be available"
    echo "  Run manually when database is available:"
    echo "  npx prisma migrate deploy"
fi

# Step 3: Seed Marketplace Offering
echo ""
echo "Step 3: Seeding marketplace offering..."
if npx ts-node scripts/seed-as4-settlement-marketplace-offering.ts; then
    echo "✓ Marketplace offering seeded"
else
    echo "⚠ Seeding failed - database may not be available"
    echo "  Run manually when database is available:"
    echo "  npx ts-node scripts/seed-as4-settlement-marketplace-offering.ts"
fi

# Step 4: Verify TypeScript Compilation
echo ""
echo "Step 4: Verifying TypeScript compilation..."
if npx tsc --noEmit; then
    echo "✓ TypeScript compilation successful"
else
    echo "✗ TypeScript compilation failed"
    exit 1
fi

# Step 5: Run Linter
echo ""
echo "Step 5: Running linter..."
if npm run lint 2>&1 | grep -q "error" || [ $? -eq 0 ]; then
    echo "✓ Linter check completed"
else
    echo "⚠ Linter found issues (non-blocking)"
fi

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

echo ""
echo "========================================="
echo "Deployment verification complete!"
echo "========================================="
echo ""
echo "Next steps:"
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 ""
