/**
 * PaymentTypeController - Controller de Formas de Pago
 *
 * Endpoints REST para gestion de formas de pago del SAT (PPD, PUE).
 *
 * @module Fiscal
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  PaymentTypeService,
  CreatePaymentTypeDto,
  UpdatePaymentTypeDto,
  PaymentTypeFilters,
} from '../services/payment-type.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { PaymentType } from '../entities/payment-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 createPaymentTypeController(dataSource: DataSource): Router {
  const router = Router();

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

  // Services
  const paymentTypeService = new PaymentTypeService(paymentTypeRepository);
  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 /payment-types
   * List payment 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: PaymentTypeFilters = {};
      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 paymentTypeService.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 /payment-types/active
   * Get all active payment 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 paymentTypeService.findAllActive(getContext(req));
      res.status(200).json({ success: true, data: types });
    } catch (error) {
      next(error);
    }
  });

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

  /**
   * GET /payment-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 paymentTypeService.findByCode(req.params.code);
      if (!type) {
        res.status(404).json({ error: 'Not Found', message: 'Payment type not found' });
        return;
      }

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

  /**
   * GET /payment-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 paymentTypeService.findById(getContext(req), req.params.id);
      if (!type) {
        res.status(404).json({ error: 'Not Found', message: 'Payment type not found' });
        return;
      }

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

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

      const type = await paymentTypeService.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 /payment-types/:id
   * Update payment 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: UpdatePaymentTypeDto = req.body;
      const type = await paymentTypeService.update(getContext(req), req.params.id, dto);

      if (!type) {
        res.status(404).json({ error: 'Not Found', message: 'Payment 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 /payment-types/:id
   * Deactivate payment 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 paymentTypeService.deactivate(getContext(req), req.params.id);
      if (!deactivated) {
        res.status(404).json({ error: 'Not Found', message: 'Payment type not found' });
        return;
      }

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

  return router;
}

export default createPaymentTypeController;
