/**
 * CfdiUseController - Controller de Usos de CFDI
 *
 * Endpoints REST para gestion de usos de CFDI del SAT.
 *
 * @module Fiscal
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  CfdiUseService,
  CreateCfdiUseDto,
  UpdateCfdiUseDto,
  CfdiUseFilters,
} from '../services/cfdi-use.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { CfdiUse } from '../entities/cfdi-use.entity';
import { 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 createCfdiUseController(dataSource: DataSource): Router {
  const router = Router();

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

  // Services
  const cfdiUseService = new CfdiUseService(cfdiUseRepository);
  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 /cfdi-uses
   * List CFDI uses 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: CfdiUseFilters = {};
      if (req.query.appliesTo) filters.appliesTo = req.query.appliesTo as PersonType;
      if (req.query.regimeCode) filters.regimeCode = req.query.regimeCode 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 cfdiUseService.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 /cfdi-uses/active
   * Get all active CFDI uses
   */
  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 uses = await cfdiUseService.findAllActive(getContext(req));
      res.status(200).json({ success: true, data: uses });
    } catch (error) {
      next(error);
    }
  });

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

  /**
   * GET /cfdi-uses/person-type/:personType
   * Get uses 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 uses = await cfdiUseService.findByPersonType(getContext(req), personType);
      res.status(200).json({ success: true, data: uses });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /cfdi-uses/regime/:regimeCode
   * Get uses compatible with a fiscal regime
   */
  router.get('/regime/:regimeCode', 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 uses = await cfdiUseService.findByRegime(getContext(req), req.params.regimeCode);
      res.status(200).json({ success: true, data: uses });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /cfdi-uses/validate-compatibility
   * Validate use-regime compatibility
   */
  router.post('/validate-compatibility', 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 { useCode, regimeCode } = req.body;
      if (!useCode || !regimeCode) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'useCode and regimeCode are required',
        });
        return;
      }

      const validation = await cfdiUseService.validateCompatibility(getContext(req), useCode, regimeCode);
      res.status(200).json({ success: true, data: validation });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /cfdi-uses/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 use = await cfdiUseService.findByCode(req.params.code);
      if (!use) {
        res.status(404).json({ error: 'Not Found', message: 'CFDI use not found' });
        return;
      }

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

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

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

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

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

  /**
   * PUT /cfdi-uses/:id
   * Update CFDI use
   */
  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: UpdateCfdiUseDto = req.body;
      const use = await cfdiUseService.update(getContext(req), req.params.id, dto);

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

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

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

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

  return router;
}

export default createCfdiUseController;
