#!/bin/bash

# Script để export Flutter web app thành HTML/CSS cho production
# Tạo package sẵn sàng để deploy cho bên web

echo "🚀 Exporting Flutter web app for production..."

# Kill server cũ trên port 8080 (nếu có)
echo "🛑 Stopping any existing server on :8080..."
lsof -i :8080 | awk 'NR>1 {print $2}' | xargs kill -9 2>/dev/null || true

# Clear cache build để tránh dính SW/cache cũ
echo "🧹 Clearing build caches..."
flutter clean
rm -rf .dart_tool build
flutter pub get

# Install web dependencies for x-app-sdk
echo "📦 Installing web dependencies for x-app-sdk..."
cd web
if [ -f "package.json" ]; then
    npm install
    if [ $? -eq 0 ]; then
        echo "✅ Web dependencies installed successfully!"
    else
        echo "⚠️ Warning: Failed to install web dependencies, continuing anyway..."
    fi
else
    echo "⚠️ No package.json found in web directory, skipping npm install"
fi
cd ..

# Tạo thư mục export
EXPORT_DIR="web_export_$(date +%Y%m%d_%H%M%S)"
echo "📁 Creating export directory: $EXPORT_DIR"
mkdir -p "$EXPORT_DIR"

# Build web app (prefer HTML renderer). If your Flutter doesn't support --web-renderer, the dart-define will keep HTML path.
echo "🔨 Building Flutter web app (HTML renderer preferred)..."
flutter build web --release --source-maps --dart-define=FLUTTER_WEB_USE_SKIA=false

if [ $? -eq 0 ]; then
    echo "✅ Build thành công!"
    # Copy toàn bộ nội dung từ build/web
    echo "📦 Copying web files..."
    cp -r build/web/* "$EXPORT_DIR/"
    
    # Copy firebase-messaging-sw.js nếu chưa có
    if [ ! -f "$EXPORT_DIR/firebase-messaging-sw.js" ]; then
        cp web/firebase-messaging-sw.js "$EXPORT_DIR/"
    fi
    
    # Tạo file test để demo URL parameters
    cat > "$EXPORT_DIR/test_urls.html" << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>Test URL Parameters</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-link { display: block; margin: 10px 0; padding: 10px; background: #f0f0f0; text-decoration: none; color: #333; }
        .test-link:hover { background: #e0e0e0; }
    </style>
</head>
<body>
    <h1>Test URL Parameters</h1>
    <p>Click các link dưới đây để test URL parameters:</p>
    
    <a href="?token=abc123" class="test-link">Test với token: abc123</a>
    <a href="?token=abc123&userId=user456" class="test-link">Test với token + userId</a>
    <a href="?token=admin789&userId=admin001" class="test-link">Test với admin token</a>
    <a href="/" class="test-link">Test không có parameters (onboarding)</a>
    
    <h2>Debug Info:</h2>
    <div id="debug-info"></div>
    
    <script>
        // Hiển thị thông tin debug
        const urlParams = new URLSearchParams(window.location.search);
        const token = urlParams.get('token');
        const userId = urlParams.get('userId');
        
        document.getElementById('debug-info').innerHTML = `
            <p><strong>Current URL:</strong> ${window.location.href}</p>
            <p><strong>Token:</strong> ${token || 'None'}</p>
            <p><strong>UserId:</strong> ${userId || 'None'}</p>
            <p><strong>localStorage url_token:</strong> ${localStorage.getItem('url_token') || 'None'}</p>
            <p><strong>localStorage url_user_id:</strong> ${localStorage.getItem('url_user_id') || 'None'}</p>
        `;
    </script>
</body>
</html>
EOF
    echo "📝 Created test_urls.html for testing"
    
    # Tạo file README cho bên web
    cat > "$EXPORT_DIR/README_DEPLOYMENT.md" << 'EOF'
# MyPoint Flutter Web App - Deployment Guide

## Cấu trúc thư mục
- `index.html` - File chính của ứng dụng
- `main.dart.js` - JavaScript code của Flutter app
- `flutter_bootstrap.js` - Flutter bootstrap script
- `canvaskit/` - Flutter rendering engine
- `assets/` - Images, fonts, và data files
- `firebase-messaging-sw.js` - Firebase service worker

## Yêu cầu server
- Web server hỗ trợ serving static files
- HTTPS được khuyến nghị cho PWA features
- CORS headers nếu cần thiết cho API calls

## Cấu hình server
1. Serve tất cả files từ thư mục này
2. Đảm bảo MIME types đúng:
   - `.js` files: `application/javascript`
   - `.wasm` files: `application/wasm`
   - `.json` files: `application/json`
   - `.png/.jpg` files: `image/*`

## Environment Variables
App sử dụng các biến môi trường từ `assets/config/env.json`
Có thể override bằng query parameters: `?env=production`

## Firebase Configuration
Firebase config được load từ `firebase_options.dart`
Đảm bảo Firebase project được cấu hình đúng cho domain này.

## x-app-sdk Integration
App được tích hợp với x-app-sdk để giao tiếp với Super App:
- **Token retrieval**: Lấy token từ Super App
- **User info**: Lấy thông tin user từ Super App
- **Fallback methods**: URL parameters và localStorage
- **Retry mechanism**: Tối đa 3 lần retry

### Test x-app-sdk:
1. Mở `test_urls.html` để test với URL parameters
2. Kiểm tra console log để debug
3. Test với Super App environment

## CORS Configuration
App cần CORS headers để gọi API:
```
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Accept, Origin
```

## Troubleshooting
- Nếu có lỗi CORS, cấu hình server để allow origin của domain
- Nếu có lỗi Firebase, kiểm tra domain trong Firebase console
- Nếu có lỗi assets, đảm bảo đường dẫn relative đúng
- Nếu có lỗi x-app-sdk, kiểm tra Super App environment
EOF

    # Tạo file .htaccess cho Apache
    cat > "$EXPORT_DIR/.htaccess" << 'EOF'
# Apache configuration for Flutter web app

# Enable compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/wasm
</IfModule>

# Set correct MIME types
AddType application/javascript .js
AddType application/wasm .wasm
AddType application/json .json

# Cache static assets
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType application/wasm "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
</IfModule>

# Security headers
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# CORS headers for API calls
<IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With, Accept, Origin"
    Header always set Access-Control-Allow-Credentials "true"
</IfModule>
EOF

    # Tạo file nginx.conf cho Nginx
    cat > "$EXPORT_DIR/nginx.conf" << 'EOF'
# Nginx configuration for Flutter web app

server {
    listen 80;
    server_name your-domain.com;
    root /path/to/web_export;
    index index.html;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json application/wasm;

    # Cache static assets
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|wasm)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Handle Flutter routes
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Security headers
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options DENY;
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy "strict-origin-when-cross-origin";

    # CORS headers for API calls
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
    add_header Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With, Accept, Origin";
    add_header Access-Control-Allow-Credentials "true";
}
EOF

    # Tạo file package.json cho Node.js hosting
    cat > "$EXPORT_DIR/package.json" << 'EOF'
{
  "name": "mypoint-flutter-web",
  "version": "1.0.0",
  "description": "MyPoint Flutter Web Application",
  "main": "index.html",
  "scripts": {
    "start": "npx serve -s . -l 3000",
    "build": "echo 'Already built by Flutter'",
    "serve": "npx serve -s . -l 3000"
  },
  "dependencies": {
    "serve": "^14.0.0"
  },
  "engines": {
    "node": ">=14.0.0"
  }
}
EOF

    # Tạo file docker-compose.yml cho Docker deployment
    cat > "$EXPORT_DIR/docker-compose.yml" << 'EOF'
version: '3.8'
services:
  mypoint-web:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - .:/usr/share/nginx/html:ro
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    restart: unless-stopped
EOF

    # Tạo file Dockerfile
    cat > "$EXPORT_DIR/Dockerfile" << 'EOF'
FROM nginx:alpine

# Copy web files
COPY . /usr/share/nginx/html/

# Copy nginx configuration
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Expose port
EXPOSE 80

# Start nginx
CMD ["nginx", "-g", "daemon off;"]
EOF

    # Tạo zip file để dễ dàng transfer
    echo "📦 Creating zip package..."
    zip -r "${EXPORT_DIR}.zip" "$EXPORT_DIR"
    
    echo ""
    echo "✅ Export hoàn thành!"
    echo "📁 Thư mục export: $EXPORT_DIR"
    echo "📦 Zip file: ${EXPORT_DIR}.zip"
    echo ""
    echo "🚀 Cách deploy:"
    echo "1. Upload toàn bộ nội dung thư mục $EXPORT_DIR lên web server"
    echo "2. Cấu hình web server theo hướng dẫn trong README_DEPLOYMENT.md"
    echo "3. Hoặc sử dụng Docker: docker-compose up -d"
    echo "4. Hoặc sử dụng Node.js: npm install && npm start"
    echo ""
    echo "🔧 X-App-SDK Integration:"
    echo "- Mini app đã được tích hợp x-app-sdk để lấy token và user info từ Super App"
    echo "- Super App cần expose window.getToken() và window.getInfo() methods"
    echo "- Retry mechanism: Tối đa 3 lần retry cho Super App data"
    echo "- Fallback methods: URL parameters và localStorage"
    echo "- Xem chi tiết trong X_APP_SDK_INTEGRATION.md"
    echo ""
    echo "🌐 Test local: cd $EXPORT_DIR && python3 -m http.server 8080"
    echo "💡 Tip: Nếu muốn auto-run server, chạy: (cd $EXPORT_DIR && python3 -m http.server 8080 &)"
    
else
    echo "❌ Build thất bại!"
    exit 1
fi
