/**
 * AsignacionController - REST API for housing assignments
 *
 * Endpoints para gestión de asignaciones de vivienda INFONAVIT.
 *
 * @module Infonavit
 * @routes /api/asignaciones
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { AsignacionService, AsignacionFilters } from '../services/asignacion.service';
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';

/**
 * Service context for multi-tenant operations
 */
interface ServiceContext {
  tenantId: string;
  userId?: string;
}

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

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

  // Services
  const service = new AsignacionService(dataSource);
  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/asignaciones
   * List assignments 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: AsignacionFilters = {};
      if (req.query.ofertaId) filters.ofertaId = req.query.ofertaId as string;
      if (req.query.derechohabienteId) filters.derechohabienteId = req.query.derechohabienteId as string;
      if (req.query.status) filters.status = req.query.status as AsignacionFilters['status'];
      if (req.query.dateFrom) filters.dateFrom = new Date(req.query.dateFrom as string);
      if (req.query.dateTo) filters.dateTo = new Date(req.query.dateTo 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: {
          total: result.total,
          page: result.page,
          limit: result.limit,
          totalPages: result.totalPages,
        },
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /api/asignaciones/:id
   * Get assignment 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 asignacion = await service.findWithDetails(getContext(req), req.params.id);
      if (!asignacion) {
        res.status(404).json({ error: 'Not Found', message: 'Assignment not found' });
        return;
      }

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

  /**
   * POST /api/asignaciones
   * Create new assignment
   */
  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 asignacion = await service.create(getContext(req), {
        ofertaId: req.body.ofertaId,
        derechohabienteId: req.body.derechohabienteId,
        assignmentDate: new Date(req.body.assignmentDate),
        creditAmount: req.body.creditAmount,
        subsidyAmount: req.body.subsidyAmount,
        downPayment: req.body.downPayment,
        notes: req.body.notes,
      });

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

  /**
   * POST /api/asignaciones/:id/approve
   * Approve assignment
   */
  router.post('/:id/approve', 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 asignacion = await service.approve(getContext(req), req.params.id);
      if (!asignacion) {
        res.status(404).json({ error: 'Not Found', message: 'Assignment not found' });
        return;
      }

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

  /**
   * POST /api/asignaciones/:id/formalize
   * Formalize assignment
   */
  router.post('/:id/formalize', 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 asignacion = await service.formalize(getContext(req), req.params.id, {
        formalizationDate: new Date(req.body.formalizationDate),
        notaryName: req.body.notaryName,
        notaryNumber: req.body.notaryNumber,
        deedNumber: req.body.deedNumber,
        deedDate: new Date(req.body.deedDate),
      });

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

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

  /**
   * POST /api/asignaciones/:id/deliver
   * Deliver housing
   */
  router.post('/:id/deliver', 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 asignacion = await service.deliver(
        getContext(req),
        req.params.id,
        new Date(req.body.deliveryDate)
      );

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

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

  /**
   * POST /api/asignaciones/:id/cancel
   * Cancel assignment
   */
  router.post('/:id/cancel', 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 asignacion = await service.cancel(getContext(req), req.params.id, req.body.reason);
      if (!asignacion) {
        res.status(404).json({ error: 'Not Found', message: 'Assignment not found' });
        return;
      }

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

  return router;
}
