#!/bin/bash

# Fix TypeScript Call interface mismatch

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${BLUE}[INFO]${NC} Fixing TypeScript Call interface issues..."

cd /opt/airwavepbx

# Update the calls page to fix the type mismatch
echo -e "${BLUE}[INFO]${NC} Updating calls page component..."
cat > src/app/dashboard/calls/page.tsx << 'EOF'
'use client';

import { useEffect, useState } from 'react';
import Layout from '@/components/Layout';
import { apiClient, type Call as ApiCall } from '@/lib/api';
import toast from 'react-hot-toast';

// Component uses a different interface than the API
interface Call {
  id: string;
  caller_id_name: string;
  caller_id_number: string;
  peer_caller_id_name: string;
  peer_caller_id_number: string;
  status: string;
  creation_time: string;
  answer_time?: string;
}

export default function ActiveCallsPage() {
  const [calls, setCalls] = useState<Call[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadCalls();
    
    // Refresh every 5 seconds
    const interval = setInterval(loadCalls, 5000);
    return () => clearInterval(interval);
  }, []);

  const loadCalls = async () => {
    try {
      const activeCalls = await apiClient.getActiveCalls();
      
      // Map API response to component interface
      const mappedCalls: Call[] = activeCalls.map(apiCall => ({
        id: apiCall.id,
        caller_id_name: apiCall.caller_name,
        caller_id_number: apiCall.caller_id,
        peer_caller_id_name: apiCall.called_name,
        peer_caller_id_number: apiCall.called_id,
        status: apiCall.status,
        creation_time: apiCall.start_time,
        answer_time: apiCall.start_time // Using start_time as answer_time for now
      }));
      
      setCalls(mappedCalls);
    } catch (error) {
      console.error('Failed to load calls:', error);
      if (loading) { // Only show error on initial load
        toast.error('Failed to load active calls');
      }
    } finally {
      setLoading(false);
    }
  };

  const formatDuration = (startTime: string) => {
    const start = new Date(startTime).getTime();
    const now = new Date().getTime();
    const seconds = Math.floor((now - start) / 1000);
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  return (
    <Layout>
      <div>
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold text-gray-900">Active Calls</h1>
          <div className="flex items-center space-x-2">
            <div className="animate-pulse h-3 w-3 bg-green-500 rounded-full"></div>
            <span className="text-sm text-gray-600">Live</span>
          </div>
        </div>

        {loading ? (
          <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
          </div>
        ) : calls.length === 0 ? (
          <div className="bg-white rounded-lg shadow p-8 text-center">
            <div className="text-gray-400 text-6xl mb-4">📞</div>
            <p className="text-gray-500">No active calls</p>
          </div>
        ) : (
          <div className="bg-white shadow rounded-lg overflow-hidden">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Caller
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Callee
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Status
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Duration
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {calls.map((call) => (
                  <tr key={call.id}>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div>
                        <div className="text-sm font-medium text-gray-900">
                          {call.caller_id_name || 'Unknown'}
                        </div>
                        <div className="text-sm text-gray-500">
                          {call.caller_id_number}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div>
                        <div className="text-sm font-medium text-gray-900">
                          {call.peer_caller_id_name || 'Unknown'}
                        </div>
                        <div className="text-sm text-gray-500">
                          {call.peer_caller_id_number}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                        call.status === 'Up' 
                          ? 'bg-green-100 text-green-800' 
                          : 'bg-yellow-100 text-yellow-800'
                      }`}>
                        {call.status}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {formatDuration(call.answer_time || call.creation_time)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </Layout>
  );
}
EOF

# Now try to build again
echo -e "${BLUE}[INFO]${NC} Attempting build again..."
npm run build

if [ $? -eq 0 ]; then
    echo -e "${GREEN}[SUCCESS]${NC} Build completed successfully!"
    
    # Continue with starting services
    echo -e "${BLUE}[INFO]${NC} Starting AirwavePBX services..."
    
    # Load environment
    source /etc/airwavepbx/airwavepbx.env
    
    # Create ecosystem file if it doesn't exist
    if [ ! -f ecosystem.config.js ]; then
        cat > ecosystem.config.js << EOF
module.exports = {
  apps: [
    {
      name: 'airwavepbx-frontend',
      script: 'npm',
      args: 'start',
      cwd: '/opt/airwavepbx',
      env_file: '/etc/airwavepbx/airwavepbx.env'
    },
    {
      name: 'airwavepbx-api',
      script: 'api/server.js',
      cwd: '/opt/airwavepbx',
      env_file: '/etc/airwavepbx/airwavepbx.env'
    }
  ]
};
EOF
    fi
    
    # Start services with PM2
    pm2 start ecosystem.config.js
    pm2 save
    pm2 startup systemd -u root --hp /root
    
    # Configure Nginx if needed
    if [ ! -f /etc/nginx/sites-available/airwavepbx ]; then
        echo -e "${BLUE}[INFO]${NC} Configuring Nginx..."
        
        cat > /etc/nginx/sites-available/airwavepbx << NGINX_EOF
server {
    listen 80;
    server_name $DOMAIN;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }

    location /api/ {
        proxy_pass http://localhost:3001/api/;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
    }

    location /ws {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
    }
}
NGINX_EOF

        ln -sf /etc/nginx/sites-available/airwavepbx /etc/nginx/sites-enabled/
        rm -f /etc/nginx/sites-enabled/default
        nginx -t && systemctl reload nginx
    fi
    
    # Check service status
    sleep 5
    pm2 status
    
    echo -e "${GREEN}[SUCCESS]${NC} AirwavePBX installation completed!"
    echo
    echo "Access your system at: http://$DOMAIN"
    echo "Username: admin"
    echo "Password: admin"
    echo
    echo "To set up SSL, run: sudo certbot --nginx -d $DOMAIN"
    
else
    echo -e "${RED}[ERROR]${NC} Build still failing. Checking for more issues..."
fi
EOF