import { Router, Request, Response } from 'express';
import { aiService } from '@services/ai.service';
import { authenticateToken } from '../middlewares/auth.middleware';
import logger from '@utils/logger';

const router = Router();

/**
 * @route   GET /api/v1/ai/status
 * @desc    Get AI service status
 * @access  Private (Admin only)
 */
router.get('/status', authenticateToken, async (req: Request, res: Response) => {
  try {
    const isAvailable = aiService.isAvailable();
    const provider = aiService.getProviderName();
    
    res.json({
      success: true,
      data: {
        available: isAvailable,
        provider: provider,
        status: isAvailable ? 'active' : 'unavailable'
      }
    });
  } catch (error: any) {
    logger.error('[AI Routes] Error getting status:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to get AI status'
    });
  }
});

/**
 * @route   POST /api/v1/ai/reinitialize
 * @desc    Reinitialize AI service (after config change)
 * @access  Private (Admin only)
 */
router.post('/reinitialize', authenticateToken, async (req: Request, res: Response): Promise<void> => {
  try {
    // Check if user is admin
    const userRole = (req as any).user?.role;
    const isAdmin = userRole?.toLowerCase() === 'admin';
    if (!isAdmin) {
      res.status(403).json({
        success: false,
        error: 'Only admins can reinitialize AI service'
      });
      return;
    }

    await aiService.reinitialize();
    
    const isAvailable = aiService.isAvailable();
    const provider = aiService.getProviderName();
    
    res.json({
      success: true,
      message: 'AI service reinitialized successfully',
      data: {
        available: isAvailable,
        provider: provider
      }
    });
  } catch (error: any) {
    logger.error('[AI Routes] Error reinitializing:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to reinitialize AI service'
    });
  }
});

export default router;

