/**
 * Analysis Routes for Redirect Intelligence v2
 * 
 * Provides dedicated endpoints for SSL, SEO, and Security analysis
 */

import express from 'express';
import { z } from 'zod';
import rateLimit from 'express-rate-limit';
import { SSLAnalyzerService } from '../services/ssl-analyzer.service';
import { SEOAnalyzerService } from '../services/seo-analyzer.service';
import { SecurityAnalyzerService } from '../services/security-analyzer.service';
import { optionalAuth, requireAuth, AuthenticatedRequest } from '../middleware/auth.middleware';
import { logger } from '../lib/logger';
import { prisma } from '../lib/prisma';

const router = express.Router();

// Initialize analysis services
const sslAnalyzer = new SSLAnalyzerService();
const seoAnalyzer = new SEOAnalyzerService();
const securityAnalyzer = new SecurityAnalyzerService();

// Rate limiting for analysis endpoints
const analysisLimiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 1 hour
  max: 100, // Lower limit for resource-intensive analysis
  message: {
    success: false,
    error: 'Analysis rate limit exceeded',
    message: 'Too many analysis requests. Please try again later.'
  },
  standardHeaders: true,
  legacyHeaders: false,
  keyGenerator: (req: AuthenticatedRequest) => {
    return req.user ? `user:${req.user.id}` : `ip:${req.ip}`;
  },
});

// Input validation schemas
const analyzeUrlSchema = z.object({
  url: z.string().url('Invalid URL format'),
});

/**
 * POST /api/v2/analyze/ssl
 * Comprehensive SSL certificate analysis
 */
router.post('/ssl', 
  optionalAuth, 
  analysisLimiter, 
  async (req: AuthenticatedRequest, res) => {
    try {
      const { url } = analyzeUrlSchema.parse(req.body);
      
      // Normalize URL
      let analyzeUrl = url;
      if (!analyzeUrl.startsWith('http://') && !analyzeUrl.startsWith('https://')) {
        analyzeUrl = 'https://' + analyzeUrl; // Default to HTTPS for SSL analysis
      }
      
      if (!analyzeUrl.startsWith('https://')) {
        return res.status(400).json({
          success: false,
          error: 'Invalid URL for SSL analysis',
          message: 'SSL analysis requires HTTPS URLs'
        });
      }
      
      const result = await sslAnalyzer.analyzeSSL(analyzeUrl);
      
      logger.info(`SSL analysis completed for: ${analyzeUrl}`, {
        userId: req.user?.id,
        securityScore: result.securityScore,
        warningsCount: result.warnings.length
      });
      
      res.json({
        success: true,
        status: 200,
        data: {
          analysis: result,
          url: analyzeUrl,
        },
        meta: {
          version: 'v2',
          analysisType: 'ssl',
          timestamp: new Date().toISOString(),
        }
      });
      
    } catch (error) {
      logger.error('SSL analysis failed:', error);
      
      if (error instanceof z.ZodError) {
        return res.status(400).json({
          success: false,
          error: 'Validation error',
          message: error.errors[0]?.message || 'Invalid input',
          details: error.errors
        });
      }
      
      res.status(500).json({
        success: false,
        error: 'SSL analysis failed',
        message: error instanceof Error ? error.message : 'Unknown error occurred'
      });
    }
  }
);

/**
 * POST /api/v2/analyze/seo
 * Comprehensive SEO analysis
 */
router.post('/seo', 
  optionalAuth, 
  analysisLimiter, 
  async (req: AuthenticatedRequest, res) => {
    try {
      const { url } = analyzeUrlSchema.parse(req.body);
      
      // Normalize URL
      let analyzeUrl = url;
      if (!analyzeUrl.startsWith('http://') && !analyzeUrl.startsWith('https://')) {
        analyzeUrl = 'https://' + analyzeUrl; // Default to HTTPS for SEO analysis
      }
      
      const result = await seoAnalyzer.analyzeSEO(analyzeUrl);
      
      logger.info(`SEO analysis completed for: ${analyzeUrl}`, {
        userId: req.user?.id,
        score: result.score,
        robotsStatus: result.flags.robotsTxtStatus,
        noindex: result.flags.noindex
      });
      
      res.json({
        success: true,
        status: 200,
        data: {
          analysis: result,
          url: analyzeUrl,
        },
        meta: {
          version: 'v2',
          analysisType: 'seo',
          timestamp: new Date().toISOString(),
        }
      });
      
    } catch (error) {
      logger.error('SEO analysis failed:', error);
      
      if (error instanceof z.ZodError) {
        return res.status(400).json({
          success: false,
          error: 'Validation error',
          message: error.errors[0]?.message || 'Invalid input',
          details: error.errors
        });
      }
      
      res.status(500).json({
        success: false,
        error: 'SEO analysis failed',
        message: error instanceof Error ? error.message : 'Unknown error occurred'
      });
    }
  }
);

/**
 * POST /api/v2/analyze/security
 * Comprehensive security analysis
 */
router.post('/security', 
  optionalAuth, 
  analysisLimiter, 
  async (req: AuthenticatedRequest, res) => {
    try {
      const { url } = analyzeUrlSchema.parse(req.body);
      
      // Normalize URL
      let analyzeUrl = url;
      if (!analyzeUrl.startsWith('http://') && !analyzeUrl.startsWith('https://')) {
        analyzeUrl = 'https://' + analyzeUrl; // Default to HTTPS for security analysis
      }
      
      const result = await securityAnalyzer.analyzeSecurity(analyzeUrl);
      
      logger.info(`Security analysis completed for: ${analyzeUrl}`, {
        userId: req.user?.id,
        securityScore: result.securityScore,
        safeBrowsing: result.safeBrowsing.status,
        vulnerabilityCount: result.vulnerabilities.length
      });
      
      res.json({
        success: true,
        status: 200,
        data: {
          analysis: result,
          url: analyzeUrl,
        },
        meta: {
          version: 'v2',
          analysisType: 'security',
          timestamp: new Date().toISOString(),
        }
      });
      
    } catch (error) {
      logger.error('Security analysis failed:', error);
      
      if (error instanceof z.ZodError) {
        return res.status(400).json({
          success: false,
          error: 'Validation error',
          message: error.errors[0]?.message || 'Invalid input',
          details: error.errors
        });
      }
      
      res.status(500).json({
        success: false,
        error: 'Security analysis failed',
        message: error instanceof Error ? error.message : 'Unknown error occurred'
      });
    }
  }
);

/**
 * POST /api/v2/analyze/comprehensive
 * Run all analyses (SSL, SEO, Security) for a URL
 */
router.post('/comprehensive', 
  optionalAuth, 
  analysisLimiter, 
  async (req: AuthenticatedRequest, res) => {
    try {
      const { url } = analyzeUrlSchema.parse(req.body);
      
      // Normalize URL
      let analyzeUrl = url;
      if (!analyzeUrl.startsWith('http://') && !analyzeUrl.startsWith('https://')) {
        analyzeUrl = 'https://' + analyzeUrl;
      }
      
      logger.info(`Starting comprehensive analysis for: ${analyzeUrl}`, {
        userId: req.user?.id
      });
      
      // Run all analyses in parallel
      const [sslResult, seoResult, securityResult] = await Promise.allSettled([
        analyzeUrl.startsWith('https://') ? sslAnalyzer.analyzeSSL(analyzeUrl) : Promise.resolve(null),
        seoAnalyzer.analyzeSEO(analyzeUrl),
        securityAnalyzer.analyzeSecurity(analyzeUrl),
      ]);
      
      // Compile results
      const analysis = {
        ssl: sslResult.status === 'fulfilled' ? sslResult.value : {
          error: sslResult.status === 'rejected' ? sslResult.reason?.message : 'SSL analysis failed'
        },
        seo: seoResult.status === 'fulfilled' ? seoResult.value : {
          error: seoResult.status === 'rejected' ? seoResult.reason?.message : 'SEO analysis failed'
        },
        security: securityResult.status === 'fulfilled' ? securityResult.value : {
          error: securityResult.status === 'rejected' ? securityResult.reason?.message : 'Security analysis failed'
        },
      };
      
      // Calculate overall score
      const scores = [
        analysis.ssl && 'securityScore' in analysis.ssl ? analysis.ssl.securityScore : 0,
        analysis.seo && 'score' in analysis.seo ? analysis.seo.score : 0,
        analysis.security && 'securityScore' in analysis.security ? analysis.security.securityScore : 0,
      ].filter(score => score > 0);
      
      const overallScore = scores.length > 0 ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length) : 0;
      
      logger.info(`Comprehensive analysis completed for: ${analyzeUrl}`, {
        userId: req.user?.id,
        overallScore,
        sslSuccess: sslResult.status === 'fulfilled',
        seoSuccess: seoResult.status === 'fulfilled',
        securitySuccess: securityResult.status === 'fulfilled'
      });
      
      res.json({
        success: true,
        status: 200,
        data: {
          analysis,
          summary: {
            overallScore,
            analysesCompleted: scores.length,
            totalAnalyses: 3,
          },
          url: analyzeUrl,
        },
        meta: {
          version: 'v2',
          analysisType: 'comprehensive',
          timestamp: new Date().toISOString(),
        }
      });
      
    } catch (error) {
      logger.error('Comprehensive analysis failed:', error);
      
      if (error instanceof z.ZodError) {
        return res.status(400).json({
          success: false,
          error: 'Validation error',
          message: error.errors[0]?.message || 'Invalid input',
          details: error.errors
        });
      }
      
      res.status(500).json({
        success: false,
        error: 'Comprehensive analysis failed',
        message: error instanceof Error ? error.message : 'Unknown error occurred'
      });
    }
  }
);

/**
 * GET /api/v2/analyze/check/:checkId
 * Get analysis results for a specific check
 */
router.get('/check/:checkId', 
  optionalAuth, 
  async (req: AuthenticatedRequest, res) => {
    try {
      const { checkId } = req.params;
      
      if (!checkId) {
        return res.status(400).json({
          success: false,
          error: 'Check ID required'
        });
      }
      
      // Get check with all analysis data
      const check = await prisma.check.findUnique({
        where: { id: checkId },
        include: {
          hops: {
            orderBy: { hopIndex: 'asc' }
          },
          sslInspections: true,
          seoFlags: true,
          securityFlags: true,
        }
      });
      
      if (!check) {
        return res.status(404).json({
          success: false,
          error: 'Check not found',
          message: 'The requested check does not exist or you do not have access to it'
        });
      }
      
      // TODO: Add proper permission checking in future phases
      
      res.json({
        success: true,
        status: 200,
        data: {
          check: {
            id: check.id,
            inputUrl: check.inputUrl,
            finalUrl: check.finalUrl,
            status: check.status,
            startedAt: check.startedAt,
            finishedAt: check.finishedAt,
            totalTimeMs: check.totalTimeMs,
          },
          analysis: {
            ssl: check.sslInspections,
            seo: check.seoFlags,
            security: check.securityFlags,
          },
          hops: check.hops,
        },
        meta: {
          version: 'v2',
          checkId: check.id,
          timestamp: new Date().toISOString(),
        }
      });
      
    } catch (error) {
      logger.error('Failed to retrieve check analysis:', error);
      res.status(500).json({
        success: false,
        error: 'Failed to retrieve analysis',
        message: error instanceof Error ? error.message : 'Unknown error occurred'
      });
    }
  }
);

export default router;
