/**
 * WebhookEndpointController - Webhook Endpoint REST API
 *
 * REST endpoints for managing webhook endpoint configurations.
 *
 * @module Webhooks
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  WebhookEndpointService,
  CreateEndpointDto,
  UpdateEndpointDto,
  EndpointFilters,
} from '../services/endpoint.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { WebhookEndpoint, AuthType } from '../entities/endpoint.entity';
import { WebhookEndpointLog } from '../entities/endpoint-log.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 createWebhookEndpointController(dataSource: DataSource): Router {
  const router = Router();

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

  // Services
  const endpointService = new WebhookEndpointService(endpointRepository, logRepository);
  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/endpoints
   * List all webhook endpoints
   */
  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: EndpointFilters = {
        page: parseInt(req.query.page as string) || 1,
        limit: Math.min(parseInt(req.query.limit as string) || 20, 100),
      };

      if (req.query.isActive !== undefined) {
        filters.isActive = req.query.isActive === 'true';
      }
      if (req.query.isVerified !== undefined) {
        filters.isVerified = req.query.isVerified === 'true';
      }
      if (req.query.authType) {
        filters.authType = req.query.authType as AuthType;
      }
      if (req.query.search) {
        filters.search = req.query.search as string;
      }

      const result = await endpointService.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/endpoints/stats
   * Get endpoint 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;
      }

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

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

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

  /**
   * GET /webhooks/endpoints/:id/logs
   * Get endpoint activity logs
   */
  router.get('/:id/logs', 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 logs = await endpointService.getLogs(getContext(req), req.params.id, limit);

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

  /**
   * POST /webhooks/endpoints
   * Create new webhook endpoint
   */
  router.post('/', 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: CreateEndpointDto = req.body;

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

      const endpoint = await endpointService.create(getContext(req), dto);
      res.status(201).json({ success: true, data: endpoint });
    } catch (error) {
      if (error instanceof Error && error.message.includes('already exists')) {
        res.status(409).json({ error: 'Conflict', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * PUT /webhooks/endpoints/:id
   * Update webhook endpoint
   */
  router.put('/:id', 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: UpdateEndpointDto = req.body;
      const endpoint = await endpointService.update(getContext(req), req.params.id, dto);

      if (!endpoint) {
        res.status(404).json({ error: 'Not Found', message: 'Endpoint not found' });
        return;
      }

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

  /**
   * PATCH /webhooks/endpoints/:id
   * Partial update webhook endpoint
   */
  router.patch('/:id', 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: UpdateEndpointDto = req.body;
      const endpoint = await endpointService.update(getContext(req), req.params.id, dto);

      if (!endpoint) {
        res.status(404).json({ error: 'Not Found', message: 'Endpoint not found' });
        return;
      }

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

  /**
   * POST /webhooks/endpoints/:id/activate
   * Activate endpoint
   */
  router.post('/:id/activate', 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 endpoint = await endpointService.activate(getContext(req), req.params.id);
      if (!endpoint) {
        res.status(404).json({ error: 'Not Found', message: 'Endpoint not found' });
        return;
      }

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

  /**
   * POST /webhooks/endpoints/:id/deactivate
   * Deactivate endpoint
   */
  router.post('/:id/deactivate', 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 endpoint = await endpointService.deactivate(getContext(req), req.params.id);
      if (!endpoint) {
        res.status(404).json({ error: 'Not Found', message: 'Endpoint not found' });
        return;
      }

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

  /**
   * POST /webhooks/endpoints/:id/verify
   * Verify endpoint by sending test request
   */
  router.post('/:id/verify', 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 endpointService.verify(getContext(req), req.params.id);

      if (!result.success) {
        res.status(422).json({ error: 'Unprocessable Entity', message: result.message });
        return;
      }

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

  /**
   * POST /webhooks/endpoints/:id/regenerate-secret
   * Regenerate signing secret
   */
  router.post('/:id/regenerate-secret', 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 endpointService.regenerateSecret(getContext(req), req.params.id);
      if (!result) {
        res.status(404).json({ error: 'Not Found', message: 'Endpoint not found' });
        return;
      }

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

  /**
   * DELETE /webhooks/endpoints/:id
   * Delete webhook endpoint
   */
  router.delete('/:id', 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 deleted = await endpointService.delete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Endpoint not found' });
        return;
      }

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

  return router;
}

export default createWebhookEndpointController;
