// WAPL API Routes

import { Router } from 'express';
import { waplService } from './wapl.service';
import { patternLibraryService } from './pattern-library.service';
import { patternCompilerService } from './pattern-compiler.service';

const router = Router();

/**
 * @swagger
 * /api/v1/wapl/initialize:
 *   post:
 *     summary: Initialize WAPL with default patterns
 *     tags: [WAPL]
 */
router.post('/initialize', async (req, res, next) => {
  try {
    await waplService.initialize();
    res.json({ message: 'WAPL initialized successfully' });
  } catch (error) {
      return next(error);
  }
});

/**
 * @swagger
 * /api/v1/wapl/patterns:
 *   get:
 *     summary: Get all active patterns
 *     tags: [WAPL]
 */
router.get('/patterns', async (req, res, next) => {
  try {
    const patterns = await patternLibraryService.getActivePatterns();
    res.json(patterns);
  } catch (error) {
      return next(error);
  }
});

/**
 * @swagger
 * /api/v1/wapl/patterns/:patternCode:
 *   get:
 *     summary: Get pattern by code
 *     tags: [WAPL]
 */
router.get('/patterns/:patternCode', async (req, res, next) => {
  try {
    const pattern = await patternLibraryService.getPattern(req.params.patternCode);
    if (!pattern) {
      return res.status(404).json({ error: 'Pattern not found' });
    }
    res.json(pattern);
  } catch (error) {
      return next(error);
  }
});

/**
 * @swagger
 * /api/v1/wapl/match/:transactionId:
 *   post:
 *     summary: Match transaction against patterns
 *     tags: [WAPL]
 */
router.post('/match/:transactionId', async (req, res, next) => {
  try {
    const matches = await waplService.matchPatterns(req.params.transactionId);
    res.json(matches);
  } catch (error) {
      return next(error);
  }
});

/**
 * @swagger
 * /api/v1/wapl/alerts:
 *   get:
 *     summary: Get pattern alerts
 *     tags: [WAPL]
 */
router.get('/alerts', async (req, res, next) => {
  try {
    const alerts = await waplService.getAlerts(req.query.status as string);
    res.json(alerts);
  } catch (error) {
      return next(error);
  }
});

/**
 * @swagger
 * /api/v1/wapl/patterns:
 *   post:
 *     summary: Create or update pattern
 *     tags: [WAPL]
 */
router.post('/patterns', async (req, res, next) => {
  try {
    // Validate pattern
    const validation = patternCompilerService.validatePattern(req.body);
    if (!validation.valid) {
      return res.status(400).json({ errors: validation.errors });
    }

    const pattern = await patternLibraryService.upsertPattern(req.body);
    res.json(pattern);
  } catch (error) {
      return next(error);
  }
});

export default router;

