/**
 * TaxCategoryController - Controller de Categorias de Impuestos
 *
 * Endpoints REST para gestion de categorias de impuestos del SAT.
 *
 * @module Fiscal
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  TaxCategoryService,
  CreateTaxCategoryDto,
  UpdateTaxCategoryDto,
  TaxCategoryFilters,
} from '../services/tax-category.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { TaxCategory, TaxNature } from '../entities/tax-category.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 createTaxCategoryController(dataSource: DataSource): Router {
  const router = Router();

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

  // Services
  const taxCategoryService = new TaxCategoryService(taxCategoryRepository);
  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 /tax-categories
   * List tax categories 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: TaxCategoryFilters = {};
      if (req.query.taxNature) filters.taxNature = req.query.taxNature as TaxNature;
      if (req.query.satCode) filters.satCode = req.query.satCode 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 taxCategoryService.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 /tax-categories/active
   * Get all active tax categories
   */
  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 categories = await taxCategoryService.findAllActive(getContext(req));
      res.status(200).json({ success: true, data: categories });
    } catch (error) {
      next(error);
    }
  });

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

  /**
   * GET /tax-categories/taxes
   * Get tax categories for transferred taxes
   */
  router.get('/taxes', 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 categories = await taxCategoryService.findTaxes(getContext(req));
      res.status(200).json({ success: true, data: categories });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /tax-categories/withholdings
   * Get tax categories for withholdings
   */
  router.get('/withholdings', 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 categories = await taxCategoryService.findWithholdings(getContext(req));
      res.status(200).json({ success: true, data: categories });
    } catch (error) {
      next(error);
    }
  });

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

      const categories = await taxCategoryService.findByNature(getContext(req), nature);
      res.status(200).json({ success: true, data: categories });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /tax-categories/sat-code/:satCode
   * Get by SAT code
   */
  router.get('/sat-code/:satCode', 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 category = await taxCategoryService.findBySatCode(getContext(req), req.params.satCode);
      if (!category) {
        res.status(404).json({ error: 'Not Found', message: 'Tax category not found' });
        return;
      }

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

  /**
   * GET /tax-categories/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 category = await taxCategoryService.findByCode(req.params.code);
      if (!category) {
        res.status(404).json({ error: 'Not Found', message: 'Tax category not found' });
        return;
      }

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

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

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

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

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

  /**
   * PUT /tax-categories/:id
   * Update tax category
   */
  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: UpdateTaxCategoryDto = req.body;
      const category = await taxCategoryService.update(getContext(req), req.params.id, dto);

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

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

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

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

  return router;
}

export default createTaxCategoryController;
