/**
 * DerechohabienteController - REST API for INFONAVIT workers
 *
 * Endpoints para gestión de derechohabientes INFONAVIT.
 *
 * @module Infonavit
 * @routes /api/derechohabientes
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { DerechohabienteService, DerechohabienteFilters } from '../services/derechohabiente.service';
import { Derechohabiente } from '../entities/derechohabiente.entity';
import { HistoricoPuntos } from '../entities/historico-puntos.entity';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { User } from '../../core/entities/user.entity';
import { Tenant } from '../../core/entities/tenant.entity';
import { RefreshToken } from '../../auth/entities/refresh-token.entity';
import { ServiceContext } from '../../../shared/services/base.service';

export function createDerechohabienteController(dataSource: DataSource): Router {
  const router = Router();

  // Repositories
  const derechohabienteRepo = dataSource.getRepository(Derechohabiente);
  const historicoPuntosRepo = dataSource.getRepository(HistoricoPuntos);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);

  // Services
  const service = new DerechohabienteService(derechohabienteRepo, historicoPuntosRepo);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  // Helper for service 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 /api/derechohabientes
   * List workers with filters
   */
  router.get('/', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const filters: DerechohabienteFilters = {};
      if (req.query.nss) filters.nss = req.query.nss as string;
      if (req.query.curp) filters.curp = req.query.curp as string;
      if (req.query.status) filters.status = req.query.status as DerechohabienteFilters['status'];
      if (req.query.search) filters.search = req.query.search as string;
      if (req.query.minPoints) filters.minPoints = parseInt(req.query.minPoints as string);

      const page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);

      const result = await service.findWithFilters(getContext(req), filters, page, limit);
      res.status(200).json({ success: true, data: result.data, pagination: result.meta });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /api/derechohabientes/:id
   * Get worker with details
   */
  router.get('/:id', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const derechohabiente = await service.findWithDetails(getContext(req), req.params.id);
      if (!derechohabiente) {
        res.status(404).json({ error: 'Not Found', message: 'Worker not found' });
        return;
      }

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

  /**
   * GET /api/derechohabientes/nss/:nss
   * Get worker by NSS
   */
  router.get('/nss/:nss', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const derechohabiente = await service.findByNss(getContext(req), req.params.nss);
      if (!derechohabiente) {
        res.status(404).json({ error: 'Not Found', message: 'Worker not found' });
        return;
      }

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

  /**
   * POST /api/derechohabientes
   * Create new worker
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'infonavit'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const derechohabiente = await service.create(getContext(req), req.body);
      res.status(201).json({ success: true, data: derechohabiente });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PUT /api/derechohabientes/:id
   * Update worker
   */
  router.put('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'infonavit'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const derechohabiente = await service.update(getContext(req), req.params.id, req.body);
      if (!derechohabiente) {
        res.status(404).json({ error: 'Not Found', message: 'Worker not found' });
        return;
      }

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

  /**
   * POST /api/derechohabientes/:id/points
   * Update worker points
   */
  router.post('/:id/points', authMiddleware.authenticate, authMiddleware.authorize('admin', 'infonavit'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const { points, source, notes } = req.body;
      const derechohabiente = await service.updatePoints(getContext(req), req.params.id, points, source, notes);
      if (!derechohabiente) {
        res.status(404).json({ error: 'Not Found', message: 'Worker not found' });
        return;
      }

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

  /**
   * POST /api/derechohabientes/:id/precalify
   * Precalify worker
   */
  router.post('/:id/precalify', authMiddleware.authenticate, authMiddleware.authorize('admin', 'infonavit'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const derechohabiente = await service.precalify(getContext(req), req.params.id, {
        precalificationDate: new Date(req.body.precalificationDate),
        precalificationAmount: req.body.precalificationAmount,
        creditType: req.body.creditType,
        creditPoints: req.body.creditPoints,
      });

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

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

  /**
   * POST /api/derechohabientes/:id/qualify
   * Qualify worker
   */
  router.post('/:id/qualify', authMiddleware.authenticate, authMiddleware.authorize('admin', 'infonavit'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const derechohabiente = await service.qualify(getContext(req), req.params.id);
      if (!derechohabiente) {
        res.status(404).json({ error: 'Not Found', message: 'Worker not found' });
        return;
      }

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

  /**
   * GET /api/derechohabientes/:id/points-history
   * Get points history
   */
  router.get('/:id/points-history', authMiddleware.authenticate, async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const history = await service.getPointsHistory(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: history });
    } catch (error) {
      next(error);
    }
  });

  /**
   * DELETE /api/derechohabientes/:id
   * Soft delete worker
   */
  router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin'), async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const tenantId = req.tenantId;
      if (!tenantId) {
        res.status(400).json({ error: 'Bad Request', message: 'Tenant ID required' });
        return;
      }

      const deleted = await service.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Worker not found' });
        return;
      }

      res.status(204).send();
    } catch (error) {
      next(error);
    }
  });

  return router;
}
