/**
 * WebhookEventTypeController - Event Type REST API
 *
 * REST endpoints for managing webhook event type definitions.
 *
 * @module Webhooks
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  WebhookEventTypeService,
  CreateEventTypeDto,
  UpdateEventTypeDto,
  EventTypeFilters,
} from '../services/event-type.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { WebhookEventType, EventCategory } from '../entities/event-type.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 createWebhookEventTypeController(dataSource: DataSource): Router {
  const router = Router();

  // Repositories
  const eventTypeRepository = dataSource.getRepository(WebhookEventType);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Services
  const eventTypeService = new WebhookEventTypeService(eventTypeRepository);
  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/event-types
   * List all event types
   */
  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: EventTypeFilters = {
        page: parseInt(req.query.page as string) || 1,
        limit: Math.min(parseInt(req.query.limit as string) || 50, 200),
      };

      if (req.query.category) {
        filters.category = req.query.category as EventCategory;
      }
      if (req.query.isActive !== undefined) {
        filters.isActive = req.query.isActive === 'true';
      }
      if (req.query.isInternal !== undefined) {
        filters.isInternal = req.query.isInternal === 'true';
      }
      if (req.query.search) {
        filters.search = req.query.search as string;
      }

      const result = await eventTypeService.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/event-types/active
   * Get all active event types (for subscription selection)
   */
  router.get('/active', 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 eventTypes = await eventTypeService.getActiveEventTypes(getContext(req));
      res.status(200).json({ success: true, data: eventTypes });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/event-types/grouped
   * Get event types grouped by category
   */
  router.get('/grouped', 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 grouped = await eventTypeService.getGroupedByCategory(getContext(req));
      res.status(200).json({ success: true, data: grouped });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/event-types/category/:category
   * Get event types by category
   */
  router.get('/category/:category', 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 eventTypes = await eventTypeService.findByCategory(
        getContext(req),
        req.params.category as EventCategory
      );
      res.status(200).json({ success: true, data: eventTypes });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /webhooks/event-types/code/:code
   * Get event type by code
   */
  router.get('/code/:code', 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 eventType = await eventTypeService.findByCode(getContext(req), req.params.code);
      if (!eventType) {
        res.status(404).json({ error: 'Not Found', message: 'Event type not found' });
        return;
      }

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

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

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

  /**
   * POST /webhooks/event-types
   * Create new event type
   */
  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: CreateEventTypeDto = req.body;

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

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

  /**
   * POST /webhooks/event-types/seed
   * Seed default event types (admin only)
   */
  router.post('/seed', authMiddleware.authenticate, authMiddleware.authorize('super_admin'), async (_req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      await eventTypeService.seedDefaults();
      res.status(200).json({ success: true, message: 'Default event types seeded' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PUT /webhooks/event-types/:id
   * Update event type
   */
  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: UpdateEventTypeDto = req.body;
      const eventType = await eventTypeService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * PATCH /webhooks/event-types/:id
   * Partial update event type
   */
  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: UpdateEventTypeDto = req.body;
      const eventType = await eventTypeService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * DELETE /webhooks/event-types/:id
   * Delete event type
   */
  router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('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 eventTypeService.delete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Event type not found' });
        return;
      }

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

  return router;
}

export default createWebhookEventTypeController;
