#!/bin/bash
# AS4 Settlement Testing Script

set -e

echo "========================================="
echo "AS4 Settlement Testing Script"
echo "========================================="

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

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

# Step 2: Linter
echo ""
echo "Step 2: Linter Check..."
npm run lint || echo "⚠ Linter issues found (non-blocking)"

# Step 3: Unit Tests (if database available)
echo ""
echo "Step 3: Running Integration Tests..."
if npm test -- as4-settlement.test.ts 2>&1; then
    echo "✓ Tests passed"
else
    echo "⚠ Tests failed or database not available"
    echo "  Run tests manually when database is available:"
    echo "  npm test -- as4-settlement.test.ts"
fi

# Step 4: Verify Service Imports
echo ""
echo "Step 4: Verifying Service Imports..."
node -e "
const services = [
    'as4-security.service',
    'as4-msh.service',
    'as4-gateway.service',
    'member-directory.service',
    'instruction-intake.service',
    'posting-engine.service'
];

services.forEach(s => {
    try {
        require.resolve('./src/core/settlement/as4/' + s.replace('as4-', 'as4/'));
        console.log('✓', s);
    } catch (e) {
        try {
            require.resolve('./src/core/settlement/as4-settlement/' + s);
            console.log('✓', s);
        } catch (e2) {
            console.log('✗', s, '- not found');
        }
    }
});
" 2>&1 || echo "⚠ Service import check completed"

# Step 5: API Route Verification
echo ""
echo "Step 5: API Route Verification..."
if grep -q "/api/v1/as4/gateway" src/integration/api-gateway/app.ts && \
   grep -q "/api/v1/as4/directory" src/integration/api-gateway/app.ts && \
   grep -q "/api/v1/as4/settlement" src/integration/api-gateway/app.ts; then
    echo "✓ All AS4 routes registered"
else
    echo "✗ Some AS4 routes missing"
    exit 1
fi

# Step 6: Database Schema Verification
echo ""
echo "Step 6: Database Schema Verification..."
if grep -q "model As4Member" prisma/schema.prisma && \
   grep -q "model As4SettlementInstruction" prisma/schema.prisma; then
    echo "✓ Database models defined"
else
    echo "✗ Database models missing"
    exit 1
fi

echo ""
echo "========================================="
echo "Testing complete!"
echo "========================================="
echo ""
