import express from 'express';
import { authenticateToken, optionalAuth } from '../middleware/auth.js';
import Log from '../models/Log.js';

const router = express.Router();

/**
 * PHASE 1: Logging Endpoints
 * Handles server and browser log ingestion for debugging and monitoring
 */

// Post server logs
router.post('/', optionalAuth, async (req, res, next) => {
  try {
    const { level = 'log', message, context } = req.body;

    if (!message) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Log message is required',
        data: null
      });
    }

    // Validate log level
    const validLevels = ['log', 'warn', 'error', 'info', 'debug'];
    if (!validLevels.includes(level)) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: `Invalid log level. Must be one of: ${validLevels.join(', ')}`,
        data: null
      });
    }

    const log = await Log.create({
      userId: req.user?.id || null,
      level,
      source: 'server',
      message,
      context: context || {},
      timestamp: new Date()
    });

    res.status(201).json({
      status: 'success',
      code: 'LOG_CREATED',
      message: 'Server log recorded successfully',
      data: {
        logId: log.id,
        timestamp: log.timestamp
      }
    });
  } catch (error) {
    next(error);
  }
});

// Post browser logs (supports batch array or single log)
router.post('/browser', optionalAuth, async (req, res, next) => {
  try {
    const { logs } = req.body;

    // Handle batch array from console-forwarder
    if (logs && Array.isArray(logs)) {
      const validLevels = ['log', 'warn', 'error', 'info', 'debug'];
      const createdLogs = [];

      for (const logEntry of logs) {
        const { level = 'log', message, data, timestamp } = logEntry;

        if (!message) continue; // Skip logs without message

        if (!validLevels.includes(level)) continue; // Skip invalid levels

        const log = await Log.create({
          userId: req.user?.id || null,
          level,
          source: 'browser',
          message,
          context: { data: data || [], timestamp },
          userAgent: req.headers['user-agent'],
          url: req.headers.referer || req.headers.origin,
          timestamp: timestamp ? new Date(timestamp) : new Date()
        });

        createdLogs.push(log.id);
      }

      return res.status(201).json({
        status: 'success',
        code: 'BROWSER_LOGS_CREATED',
        message: `${createdLogs.length} browser logs recorded successfully`,
        data: {
          logIds: createdLogs,
          count: createdLogs.length
        }
      });
    }

    // Fallback: Handle single log object for backward compatibility
    const { level = 'log', message, context, userAgent, url } = req.body;

    if (!message) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: 'Log message is required',
        data: null
      });
    }

    // Validate log level
    const validLevels = ['log', 'warn', 'error', 'info', 'debug'];
    if (!validLevels.includes(level)) {
      return res.status(400).json({
        status: 'error',
        code: 'VALIDATION_ERROR',
        message: `Invalid log level. Must be one of: ${validLevels.join(', ')}`,
        data: null
      });
    }

    const log = await Log.create({
      userId: req.user?.id || null,
      level,
      source: 'browser',
      message,
      context: context || {},
      userAgent,
      url,
      timestamp: new Date()
    });

    res.status(201).json({
      status: 'success',
      code: 'BROWSER_LOG_CREATED',
      message: 'Browser log recorded successfully',
      data: {
        logId: log.id,
        timestamp: log.timestamp
      }
    });
  } catch (error) {
    next(error);
  }
});

// Get logs (admin/debugging endpoint)
router.get('/', authenticateToken, async (req, res, next) => {
  try {
    const { level, source, limit = 100, offset = 0 } = req.query;
    const where = {};

    if (level) where.level = level;
    if (source) where.source = source;

    const { count, rows } = await Log.findAndCountAll({
      where,
      limit: Math.min(parseInt(limit), 500),
      offset: parseInt(offset),
      order: [['timestamp', 'DESC']]
    });

    res.status(200).json({
      status: 'success',
      code: 'LOGS_RETRIEVED',
      message: 'Logs retrieved successfully',
      data: {
        total: count,
        limit: Math.min(parseInt(limit), 500),
        offset: parseInt(offset),
        logs: rows
      }
    });
  } catch (error) {
    next(error);
  }
});

export default router;
