/**
 * FiscalRegimeController - Controller de Regimenes Fiscales
 *
 * Endpoints REST para gestion de regimenes fiscales del SAT.
 *
 * @module Fiscal
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  FiscalRegimeService,
  CreateFiscalRegimeDto,
  UpdateFiscalRegimeDto,
  FiscalRegimeFilters,
} from '../services/fiscal-regime.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { FiscalRegime, PersonType } from '../entities/fiscal-regime.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 createFiscalRegimeController(dataSource: DataSource): Router {
  const router = Router();

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

  // Services
  const fiscalRegimeService = new FiscalRegimeService(fiscalRegimeRepository);
  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 /fiscal-regimes
   * List fiscal regimes 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: FiscalRegimeFilters = {};
      if (req.query.appliesTo) filters.appliesTo = req.query.appliesTo as PersonType;
      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 fiscalRegimeService.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 /fiscal-regimes/active
   * Get all active fiscal regimes
   */
  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 regimes = await fiscalRegimeService.findAllActive(getContext(req));
      res.status(200).json({ success: true, data: regimes });
    } catch (error) {
      next(error);
    }
  });

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

  /**
   * GET /fiscal-regimes/person-type/:personType
   * Get regimes by person type
   */
  router.get('/person-type/:personType', 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 personType = req.params.personType as PersonType;
      if (!Object.values(PersonType).includes(personType)) {
        res.status(400).json({ error: 'Bad Request', message: 'Invalid person type' });
        return;
      }

      const regimes = await fiscalRegimeService.findByPersonType(getContext(req), personType);
      res.status(200).json({ success: true, data: regimes });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /fiscal-regimes/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 regime = await fiscalRegimeService.findByCode(req.params.code);
      if (!regime) {
        res.status(404).json({ error: 'Not Found', message: 'Fiscal regime not found' });
        return;
      }

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

  /**
   * GET /fiscal-regimes/: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 regime = await fiscalRegimeService.findById(getContext(req), req.params.id);
      if (!regime) {
        res.status(404).json({ error: 'Not Found', message: 'Fiscal regime not found' });
        return;
      }

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

  /**
   * POST /fiscal-regimes
   * Create new fiscal regime
   */
  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: CreateFiscalRegimeDto = req.body;
      if (!dto.code || !dto.name) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'code and name are required',
        });
        return;
      }

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

  /**
   * PUT /fiscal-regimes/:id
   * Update fiscal regime
   */
  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: UpdateFiscalRegimeDto = req.body;
      const regime = await fiscalRegimeService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * DELETE /fiscal-regimes/:id
   * Deactivate fiscal regime
   */
  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 fiscalRegimeService.deactivate(getContext(req), req.params.id);
      if (!deactivated) {
        res.status(404).json({ error: 'Not Found', message: 'Fiscal regime not found' });
        return;
      }

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

  return router;
}

export default createFiscalRegimeController;
