/**
 * WithholdingTypeController - Controller de Tipos de Retencion
 *
 * Endpoints REST para gestion de tipos de retenciones fiscales.
 *
 * @module Fiscal
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  WithholdingTypeService,
  CreateWithholdingTypeDto,
  UpdateWithholdingTypeDto,
  WithholdingTypeFilters,
} from '../services/withholding-type.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { WithholdingType } from '../entities/withholding-type.entity';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';

interface ServiceContext {
  tenantId: string;
  userId?: string;
}

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

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

  // Services
  const withholdingTypeService = new WithholdingTypeService(withholdingTypeRepository);
  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 /withholding-types
   * List withholding types with pagination and filters
   */
  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 page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);

      const filters: WithholdingTypeFilters = {};
      if (req.query.taxCategoryId) filters.taxCategoryId = req.query.taxCategoryId as string;
      if (req.query.minRate !== undefined) filters.minRate = parseFloat(req.query.minRate as string);
      if (req.query.maxRate !== undefined) filters.maxRate = parseFloat(req.query.maxRate as string);
      if (req.query.isActive !== undefined) filters.isActive = req.query.isActive === 'true';
      if (req.query.search) filters.search = req.query.search as string;

      const result = await withholdingTypeService.findWithFilters(getContext(req), filters, page, limit);

      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 /withholding-types/active
   * Get all active withholding types
   */
  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 types = await withholdingTypeService.findAllActive(getContext(req));
      res.status(200).json({ success: true, data: types });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /withholding-types/stats
   * Get 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 withholdingTypeService.getStats(getContext(req));
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /withholding-types/tax-category/:taxCategoryId
   * Get withholding types by tax category
   */
  router.get('/tax-category/:taxCategoryId', 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 types = await withholdingTypeService.findByTaxCategory(getContext(req), req.params.taxCategoryId);
      res.status(200).json({ success: true, data: types });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /withholding-types/calculate
   * Calculate withholding amount
   */
  router.post('/calculate', 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 { amount, withholdingTypeCode, customRate } = req.body;

      if (amount === undefined || !withholdingTypeCode) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'amount and withholdingTypeCode are required',
        });
        return;
      }

      const result = await withholdingTypeService.calculateWithholdingByCode(
        getContext(req),
        amount,
        withholdingTypeCode,
        customRate
      );

      res.status(200).json({ success: true, data: result });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * GET /withholding-types/code/:code
   * Get 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 type = await withholdingTypeService.findByCode(req.params.code);
      if (!type) {
        res.status(404).json({ error: 'Not Found', message: 'Withholding type not found' });
        return;
      }

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

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

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

  /**
   * POST /withholding-types
   * Create new withholding type
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'finance'), 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: CreateWithholdingTypeDto = req.body;
      if (!dto.code || !dto.name) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'code and name are required',
        });
        return;
      }

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

  /**
   * PUT /withholding-types/:id
   * Update withholding type
   */
  router.put('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'finance'), 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: UpdateWithholdingTypeDto = req.body;
      const type = await withholdingTypeService.update(getContext(req), req.params.id, dto);

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

      res.status(200).json({ success: true, data: type });
    } catch (error) {
      if (error instanceof Error && error.message.includes('already exists')) {
        res.status(409).json({ error: 'Conflict', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * DELETE /withholding-types/:id
   * Deactivate withholding type
   */
  router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), 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 deactivated = await withholdingTypeService.deactivate(getContext(req), req.params.id);
      if (!deactivated) {
        res.status(404).json({ error: 'Not Found', message: 'Withholding type not found' });
        return;
      }

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

  return router;
}

export default createWithholdingTypeController;
