/**
 * WebhookDeliveryController - Delivery REST API
 *
 * REST endpoints for viewing and managing webhook deliveries.
 *
 * @module Webhooks
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  WebhookDeliveryService,
  DeliveryFilters,
} from '../services/delivery.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { WebhookDelivery, DeliveryStatus } from '../entities/delivery.entity';
import { WebhookEndpoint } from '../entities/endpoint.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 createWebhookDeliveryController(dataSource: DataSource): Router {
  const router = Router();

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

  // Services
  const deliveryService = new WebhookDeliveryService(deliveryRepository, endpointRepository);
  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/deliveries
   * List all deliveries
   */
  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: DeliveryFilters = {
        page: parseInt(req.query.page as string) || 1,
        limit: Math.min(parseInt(req.query.limit as string) || 20, 100),
      };

      if (req.query.endpointId) {
        filters.endpointId = req.query.endpointId as string;
      }
      if (req.query.eventType) {
        filters.eventType = req.query.eventType as string;
      }
      if (req.query.eventId) {
        filters.eventId = req.query.eventId as string;
      }
      if (req.query.status) {
        const statuses = (req.query.status as string).split(',') as DeliveryStatus[];
        filters.status = statuses.length === 1 ? statuses[0] : statuses;
      }
      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 deliveryService.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/deliveries/stats
   * Get delivery statistics
   */
  router.get('/stats', 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;
      }

      let dateRange: { from: Date; to: Date } | undefined;
      if (req.query.dateFrom && req.query.dateTo) {
        dateRange = {
          from: new Date(req.query.dateFrom as string),
          to: new Date(req.query.dateTo as string),
        };
      }

      const stats = await deliveryService.getStats(getContext(req), dateRange);
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/deliveries/pending-retries
   * Get count of pending retries
   */
  router.get('/pending-retries', 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 count = await deliveryService.getPendingRetryCount(getContext(req));
      res.status(200).json({ success: true, data: { pendingRetries: count } });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/deliveries/by-event/:eventId
   * Get deliveries for a specific event
   */
  router.get('/by-event/:eventId', 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 deliveries = await deliveryService.findByEventId(
        getContext(req),
        req.params.eventId
      );
      res.status(200).json({ success: true, data: deliveries });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/deliveries/by-endpoint/:endpointId
   * Get deliveries for a specific endpoint
   */
  router.get('/by-endpoint/:endpointId', 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 limit = Math.min(parseInt(req.query.limit as string) || 50, 200);
      const deliveries = await deliveryService.findByEndpointId(
        getContext(req),
        req.params.endpointId,
        limit
      );
      res.status(200).json({ success: true, data: deliveries });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/deliveries/:id
   * Get delivery 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 delivery = await deliveryService.findById(getContext(req), req.params.id);
      if (!delivery) {
        res.status(404).json({ error: 'Not Found', message: 'Delivery not found' });
        return;
      }

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

  /**
   * POST /webhooks/deliveries/:id/retry
   * Manually retry a failed delivery
   */
  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 delivery = await deliveryService.retry(getContext(req), req.params.id);
      if (!delivery) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'Delivery not found or not in failed status',
        });
        return;
      }

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

  /**
   * POST /webhooks/deliveries/:id/cancel
   * Cancel a pending delivery
   */
  router.post('/:id/cancel', 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 cancelled = await deliveryService.cancel(getContext(req), req.params.id);
      if (!cancelled) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'Delivery not found or not in pending/retrying status',
        });
        return;
      }

      res.status(200).json({ success: true, message: 'Delivery cancelled' });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createWebhookDeliveryController;
