/**
 * PaymentMethodController - Controller de Metodos de Pago
 *
 * Endpoints REST para gestion de metodos de pago del SAT.
 *
 * @module Fiscal
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  PaymentMethodService,
  CreatePaymentMethodDto,
  UpdatePaymentMethodDto,
  PaymentMethodFilters,
} from '../services/payment-method.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { PaymentMethod } from '../entities/payment-method.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 createPaymentMethodController(dataSource: DataSource): Router {
  const router = Router();

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

  // Services
  const paymentMethodService = new PaymentMethodService(paymentMethodRepository);
  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-methods
   * List payment methods 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: PaymentMethodFilters = {};
      if (req.query.requiresBankInfo !== undefined) filters.requiresBankInfo = req.query.requiresBankInfo === 'true';
      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 paymentMethodService.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-methods/active
   * Get all active payment methods
   */
  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 methods = await paymentMethodService.findAllActive(getContext(req));
      res.status(200).json({ success: true, data: methods });
    } catch (error) {
      next(error);
    }
  });

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

  /**
   * GET /payment-methods/requiring-bank-info
   * Get payment methods that require bank information
   */
  router.get('/requiring-bank-info', 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 methods = await paymentMethodService.findRequiringBankInfo(getContext(req));
      res.status(200).json({ success: true, data: methods });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /payment-methods/code/:code/requires-bank-info
   * Check if payment method requires bank info
   */
  router.get('/code/:code/requires-bank-info', 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 requiresBankInfo = await paymentMethodService.requiresBankInfo(getContext(req), req.params.code);
      res.status(200).json({ success: true, data: { requiresBankInfo } });
    } catch (error) {
      next(error);
    }
  });

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

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

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

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

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

      const method = await paymentMethodService.create(getContext(req), dto);
      res.status(201).json({ success: true, data: method });
    } 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-methods/:id
   * Update payment method
   */
  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: UpdatePaymentMethodDto = req.body;
      const method = await paymentMethodService.update(getContext(req), req.params.id, dto);

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

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

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

  return router;
}

export default createPaymentMethodController;
