/**
 * AvanceObraController - Controller de avances de obra
 *
 * Endpoints REST para gestión de avances físicos de obra.
 * Incluye workflow de captura -> revisión -> aprobación.
 *
 * @module Progress
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { AvanceObraService, CreateAvanceDto, AddFotoDto, AvanceFilters } from '../services/avance-obra.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;
}

/**
 * Crear router de avances de obra
 */
export function createAvanceObraController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const avanceService = new AvanceObraService(dataSource);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  // Helper para crear contexto de servicio
  const getContext = (req: Request): ServiceContext => {
    if (!req.tenantId) {
      throw new Error('Tenant ID is required');
    }
    return {
      tenantId: req.tenantId,
      userId: req.user?.sub,
    };
  };

  /**
   * GET /avances
   * Listar avances con filtros
   */
  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 page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);

      const filters: AvanceFilters = {
        loteId: req.query.loteId as string,
        departamentoId: req.query.departamentoId as string,
        conceptoId: req.query.conceptoId as string,
        status: req.query.status as any,
        dateFrom: req.query.dateFrom ? new Date(req.query.dateFrom as string) : undefined,
        dateTo: req.query.dateTo ? new Date(req.query.dateTo as string) : undefined,
      };

      const result = await avanceService.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 /avances/accumulated
   * Obtener avance acumulado por concepto
   */
  router.get('/accumulated', 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 loteId = req.query.loteId as string;
      const departamentoId = req.query.departamentoId as string;

      const progress = await avanceService.getAccumulatedProgress(getContext(req), loteId, departamentoId);
      res.status(200).json({ success: true, data: progress });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /avances/:id
   * Obtener avance por ID con fotos
   */
  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 avance = await avanceService.findWithFotos(getContext(req), req.params.id);
      if (!avance) {
        res.status(404).json({ error: 'Not Found', message: 'Progress record not found' });
        return;
      }

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

  /**
   * POST /avances
   * Crear avance (captura)
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'resident'), 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 dto: CreateAvanceDto = req.body;

      if (!dto.conceptoId) {
        res.status(400).json({ error: 'Bad Request', message: 'conceptoId is required' });
        return;
      }

      if (!dto.loteId && !dto.departamentoId) {
        res.status(400).json({ error: 'Bad Request', message: 'Either loteId or departamentoId is required' });
        return;
      }

      const avance = await avanceService.createAvance(getContext(req), dto);
      res.status(201).json({ success: true, data: avance });
    } catch (error) {
      if (error instanceof Error) {
        res.status(400).json({ error: 'Bad Request', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /avances/:id/fotos
   * Agregar foto al avance
   */
  router.post('/:id/fotos', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'resident'), 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 dto: AddFotoDto = req.body;

      if (!dto.fileUrl) {
        res.status(400).json({ error: 'Bad Request', message: 'fileUrl is required' });
        return;
      }

      const foto = await avanceService.addFoto(getContext(req), req.params.id, dto);
      res.status(201).json({ success: true, data: foto });
    } catch (error) {
      if (error instanceof Error && error.message === 'Avance not found') {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /avances/:id/review
   * Revisar avance
   */
  router.post('/:id/review', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'director'), 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 avance = await avanceService.review(getContext(req), req.params.id);
      if (!avance) {
        res.status(400).json({ error: 'Bad Request', message: 'Cannot review this progress record. It may not exist or is not in captured status.' });
        return;
      }

      res.status(200).json({ success: true, data: avance, message: 'Progress reviewed' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /avances/:id/approve
   * Aprobar avance
   */
  router.post('/:id/approve', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), 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 avance = await avanceService.approve(getContext(req), req.params.id);
      if (!avance) {
        res.status(400).json({ error: 'Bad Request', message: 'Cannot approve this progress record. It may not exist or is not in reviewed status.' });
        return;
      }

      res.status(200).json({ success: true, data: avance, message: 'Progress approved' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * POST /avances/:id/reject
   * Rechazar avance
   */
  router.post('/:id/reject', authMiddleware.authenticate, authMiddleware.authorize('admin', 'engineer', 'director'), 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 { reason } = req.body;
      if (!reason) {
        res.status(400).json({ error: 'Bad Request', message: 'reason is required' });
        return;
      }

      const avance = await avanceService.reject(getContext(req), req.params.id, reason);
      if (!avance) {
        res.status(400).json({ error: 'Bad Request', message: 'Cannot reject this progress record.' });
        return;
      }

      res.status(200).json({ success: true, data: avance, message: 'Progress rejected' });
    } catch (error) {
      next(error);
    }
  });

  /**
   * DELETE /avances/:id
   * Eliminar avance (soft delete)
   */
  router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director'), 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 avanceService.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Progress record not found' });
        return;
      }

      res.status(200).json({ success: true, message: 'Progress record deleted' });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createAvanceObraController;
