#!/bin/bash

# Security Check Script
# Run this to perform a comprehensive security check on your project

set -e

echo "🔍 Starting Security Scan..."
echo ""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    print_status "$RED" "❌ Error: package.json not found. Please run this script from the project root."
    exit 1
fi

print_status "$YELLOW" "📦 Checking for security vulnerabilities..."
echo ""

# Run security audit
if pnpm audit --audit-level=high; then
    print_status "$GREEN" "✅ No high or critical vulnerabilities found!"
else
    print_status "$RED" "⚠️  Security vulnerabilities detected!"
    echo ""
    print_status "$YELLOW" "Generating detailed report..."
    pnpm audit --json > security-report.json
    print_status "$GREEN" "Report saved to: security-report.json"
    echo ""
    print_status "$YELLOW" "To fix vulnerabilities, try:"
    echo "  pnpm security:fix"
    echo "  or update packages manually"
    exit 1
fi

echo ""
print_status "$YELLOW" "📋 Checking for outdated dependencies..."
echo ""

if pnpm outdated --recursive > /dev/null 2>&1; then
    print_status "$GREEN" "✅ All dependencies are up to date!"
else
    print_status "$YELLOW" "ℹ️  Some dependencies have updates available"
    echo ""
    pnpm outdated --recursive || true
    echo ""
    print_status "$YELLOW" "To update safely, run:"
    echo "  pnpm update:safe"
fi

echo ""
print_status "$YELLOW" "🔍 Running linter..."
echo ""

if pnpm lint; then
    print_status "$GREEN" "✅ No linting errors!"
else
    print_status "$RED" "⚠️  Linting errors found!"
    echo ""
    print_status "$YELLOW" "To fix automatically, try:"
    echo "  pnpm lint:fix"
    exit 1
fi

echo ""
print_status "$YELLOW" "📝 Running type check..."
echo ""

if pnpm type-check; then
    print_status "$GREEN" "✅ No type errors!"
else
    print_status "$RED" "⚠️  Type errors found!"
    exit 1
fi

echo ""
print_status "$GREEN" "🎉 All security checks passed!"
echo ""
print_status "$YELLOW" "Recommendations:"
echo "  1. Review any outdated dependencies"
echo "  2. Run tests: pnpm test"
echo "  3. Push changes to trigger CI/CD security scans"
echo ""

