#!/bin/bash

# ULTIMATE FIX - Let's get this done once and for all!

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

echo "========================================="
echo "AirwavePBX Ultimate Fix - v2.1"
echo "========================================="
echo

cd /opt/airwavepbx

# Fix the TypeScript error in api.ts
echo -e "${BLUE}[INFO]${NC} Fixing TypeScript errors in api.ts..."
cat > src/lib/api.ts << 'EOF'
// AirwavePBX API Client - Standalone Architecture
import axios from 'axios';

const API_BASE = '/api';

export interface User {
  id: number;
  username: string;
  email: string;
  role: string;
}

export interface Extension {
  id: number;
  extension: string;
  name: string;
  context: string;
  status?: 'online' | 'offline' | 'busy';
}

export interface Call {
  id: string;
  caller_id: string;
  caller_name: string;
  called_id: string;
  called_name: string;
  status: string;
  duration: number;
  start_time: string;
}

export interface CallLog {
  id: number;
  uniqueid: string;
  src: string;
  dst: string;
  calldate: string;
  duration: number;
  billsec: number;
  disposition: string;
}

class ApiClient {
  private token: string | null = null;

  constructor() {
    // Check for existing token
    if (typeof window !== 'undefined') {
      this.token = localStorage.getItem('auth_token');
    }
  }

  private async request(method: string, url: string, data?: any) {
    const headers: any = {
      'Content-Type': 'application/json',
    };

    if (this.token) {
      headers['Authorization'] = `Bearer ${this.token}`;
    }

    try {
      const response = await axios({
        method,
        url: `${API_BASE}${url}`,
        data,
        headers,
      });
      return response.data;
    } catch (error: any) {
      if (error.response?.status === 401) {
        // Unauthorized - clear token and redirect to login
        this.logout();
        if (typeof window !== 'undefined') {
          window.location.href = '/login';
        }
      }
      throw error;
    }
  }

  // Authentication
  async login(username: string, password: string) {
    const response = await this.request('POST', '/auth/login', { username, password });
    this.token = response.token;
    if (typeof window !== 'undefined' && this.token) {
      localStorage.setItem('auth_token', this.token);
    }
    return response;
  }

  logout() {
    this.token = null;
    if (typeof window !== 'undefined') {
      localStorage.removeItem('auth_token');
    }
  }

  isAuthenticated() {
    return !!this.token;
  }

  // Extensions
  async getExtensions(): Promise<Extension[]> {
    return this.request('GET', '/extensions');
  }

  async createExtension(data: { extension: string; name: string; context?: string }) {
    return this.request('POST', '/extensions', data);
  }

  async updateExtension(id: number, data: Partial<Extension>) {
    return this.request('PUT', `/extensions/${id}`, data);
  }

  async deleteExtension(id: number) {
    return this.request('DELETE', `/extensions/${id}`);
  }

  // Active Calls
  async getActiveCalls(): Promise<Call[]> {
    return this.request('GET', '/calls/active');
  }

  async hangupCall(callId: string) {
    return this.request('POST', `/calls/${callId}/hangup`);
  }

  // Call Logs
  async getCallLogs(limit = 100, offset = 0): Promise<CallLog[]> {
    return this.request('GET', `/calls/logs?limit=${limit}&offset=${offset}`);
  }

  // Dashboard Stats
  async getDashboardStats() {
    return this.request('GET', '/dashboard/stats');
  }

  // System
  async getSystemStatus() {
    return this.request('GET', '/system/status');
  }

  async reloadAsterisk() {
    return this.request('POST', '/system/reload');
  }
}

// Export singleton instance
export const apiClient = new ApiClient();
EOF

# Now let's run a clean build
echo -e "${BLUE}[INFO]${NC} Running clean build..."
rm -rf .next
npm run build

if [ $? -eq 0 ]; then
    echo -e "${GREEN}[SUCCESS]${NC} Build completed successfully!"
    
    # Start services
    echo -e "${BLUE}[INFO]${NC} Starting services..."
    
    # Kill any existing PM2 processes
    pm2 kill 2>/dev/null || true
    
    # Create ecosystem file
    cat > ecosystem.config.js << 'EOF'
module.exports = {
  apps: [
    {
      name: 'airwavepbx-frontend',
      script: 'npm',
      args: 'start',
      cwd: '/opt/airwavepbx',
      env_file: '/etc/airwavepbx/airwavepbx.env',
      error_file: '/var/log/airwavepbx/frontend-error.log',
      out_file: '/var/log/airwavepbx/frontend-out.log',
      merge_logs: true
    },
    {
      name: 'airwavepbx-api',
      script: 'api/server.js',
      cwd: '/opt/airwavepbx',
      env_file: '/etc/airwavepbx/airwavepbx.env',
      error_file: '/var/log/airwavepbx/api-error.log',
      out_file: '/var/log/airwavepbx/api-out.log',
      merge_logs: true
    }
  ]
};
EOF
    
    # Create log directory
    mkdir -p /var/log/airwavepbx
    
    # Start PM2
    pm2 start ecosystem.config.js
    pm2 save
    pm2 startup systemd -u root --hp /root
    
    # Configure Nginx if needed
    if [ ! -f /etc/nginx/sites-enabled/airwavepbx ]; then
        echo -e "${BLUE}[INFO]${NC} Configuring Nginx..."
        source /etc/airwavepbx/airwavepbx.env
        
        cat > /etc/nginx/sites-available/airwavepbx << NGINX_CONF
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_CONF

        ln -sf /etc/nginx/sites-available/airwavepbx /etc/nginx/sites-enabled/
        rm -f /etc/nginx/sites-enabled/default
        nginx -t && systemctl reload nginx
    fi
    
    sleep 5
    pm2 status
    
    echo
    echo -e "${GREEN}=========================================${NC}"
    echo -e "${GREEN}SUCCESS! AirwavePBX is now running!${NC}"
    echo -e "${GREEN}=========================================${NC}"
    echo
    echo "Access at: http://$DOMAIN"
    echo "Login: admin / admin"
    echo
    echo "For SSL: sudo certbot --nginx -d $DOMAIN"
    
else
    echo -e "${RED}[ERROR]${NC} Build still failing. Let me check what's wrong..."
    
    # Show the actual error
    echo -e "${BLUE}[DEBUG]${NC} Checking for specific errors..."
    
    # Let's see if there are other issues
    ls -la src/lib/
    ls -la src/app/dashboard/
fi
EOF