/**
 * WebhookEventController - Event REST API
 *
 * REST endpoints for managing webhook events.
 *
 * @module Webhooks
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  WebhookEventService,
  CreateEventDto,
  EventFilters,
} from '../services/event.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { WebhookEvent, WebhookEventStatus } from '../entities/event.entity';
import { WebhookEndpoint } from '../entities/endpoint.entity';
import { WebhookDelivery } from '../entities/delivery.entity';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';
import { ServiceContext } from '../../../shared/services/base.service';

export function createWebhookEventController(dataSource: DataSource): Router {
  const router = Router();

  // Repositories
  const eventRepository = dataSource.getRepository(WebhookEvent);
  const endpointRepository = dataSource.getRepository(WebhookEndpoint);
  const deliveryRepository = dataSource.getRepository(WebhookDelivery);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Services
  const eventService = new WebhookEventService(
    eventRepository,
    endpointRepository,
    deliveryRepository
  );
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  // Helper to create context
  const getContext = (req: Request): ServiceContext => {
    if (!req.tenantId) {
      throw new Error('Tenant ID is required');
    }
    return {
      tenantId: req.tenantId,
      userId: req.user?.sub,
    };
  };

  /**
   * GET /webhooks/events
   * List all events
   */
  router.get('/', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const filters: EventFilters = {
        page: parseInt(req.query.page as string) || 1,
        limit: Math.min(parseInt(req.query.limit as string) || 20, 100),
      };

      if (req.query.eventType) {
        filters.eventType = req.query.eventType as string;
      }
      if (req.query.status) {
        const statuses = (req.query.status as string).split(',') as WebhookEventStatus[];
        filters.status = statuses.length === 1 ? statuses[0] : statuses;
      }
      if (req.query.resourceType) {
        filters.resourceType = req.query.resourceType as string;
      }
      if (req.query.resourceId) {
        filters.resourceId = req.query.resourceId as string;
      }
      if (req.query.dateFrom) {
        filters.dateFrom = new Date(req.query.dateFrom as string);
      }
      if (req.query.dateTo) {
        filters.dateTo = new Date(req.query.dateTo as string);
      }

      const result = await eventService.findAll(getContext(req), filters);

      res.status(200).json({
        success: true,
        data: result.data,
        pagination: {
          total: result.total,
          page: result.page,
          limit: result.limit,
          totalPages: result.totalPages,
        },
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/events/counts
   * Get event counts by status
   */
  router.get('/counts', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const counts = await eventService.getCountsByStatus(getContext(req));
      res.status(200).json({ success: true, data: counts });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/events/:id
   * Get event by ID
   */
  router.get('/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const event = await eventService.findById(getContext(req), req.params.id);
      if (!event) {
        res.status(404).json({ error: 'Not Found', message: 'Event not found' });
        return;
      }

      res.status(200).json({ success: true, data: event });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /webhooks/events
   * Create and dispatch a new event
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'super_admin', 'system'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: CreateEventDto = req.body;

      if (!dto.eventType || !dto.payload) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'eventType and payload are required',
        });
        return;
      }

      const result = await eventService.createAndDispatch(getContext(req), dto);
      res.status(201).json({ success: true, data: result });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /webhooks/events/test
   * Create a test event (does not dispatch)
   */
  router.post('/test', authMiddleware.authenticate, authMiddleware.authorize('admin', 'super_admin'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const dto: CreateEventDto = req.body;

      if (!dto.eventType || !dto.payload) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'eventType and payload are required',
        });
        return;
      }

      // Only create, do not dispatch
      const event = await eventService.create(getContext(req), {
        ...dto,
        metadata: { ...dto.metadata, isTest: true },
      });
      res.status(201).json({ success: true, data: event });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /webhooks/events/:id/retry
   * Retry a failed event
   */
  router.post('/:id/retry', authMiddleware.authenticate, authMiddleware.authorize('admin', 'super_admin'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      if (!req.tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const result = await eventService.retryEvent(getContext(req), req.params.id);
      if (!result) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'Event not found or not in failed status',
        });
        return;
      }

      res.status(200).json({ success: true, data: result });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createWebhookEventController;
