/**
 * BitacoraObraController - Controller de bitácora de obra
 *
 * Endpoints REST para gestión de bitácora diaria de obra.
 *
 * @module Progress
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { BitacoraObraService, CreateBitacoraDto, UpdateBitacoraDto, BitacoraFilters } from '../services/bitacora-obra.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { BitacoraObra } from '../entities/bitacora-obra.entity';
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';

/**
 * Crear router de bitácora de obra
 */
export function createBitacoraObraController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const bitacoraService = new BitacoraObraService(bitacoraRepository);
  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 /bitacora
   * Listar entradas de bitácora por fraccionamiento
   */
  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 fraccionamientoId = req.query.fraccionamientoId as string;
      if (!fraccionamientoId) {
        res.status(400).json({ error: 'Bad Request', message: 'fraccionamientoId is 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: BitacoraFilters = {
        dateFrom: req.query.dateFrom ? new Date(req.query.dateFrom as string) : undefined,
        dateTo: req.query.dateTo ? new Date(req.query.dateTo as string) : undefined,
        hasIncidents: req.query.hasIncidents === 'true' ? true : req.query.hasIncidents === 'false' ? false : undefined,
      };

      const result = await bitacoraService.findWithFilters(getContext(req), fraccionamientoId, filters, page, limit);

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

  /**
   * GET /bitacora/stats
   * Obtener estadísticas de bitácora
   */
  router.get('/stats', 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 fraccionamientoId = req.query.fraccionamientoId as string;
      if (!fraccionamientoId) {
        res.status(400).json({ error: 'Bad Request', message: 'fraccionamientoId is required' });
        return;
      }

      const stats = await bitacoraService.getStats(getContext(req), fraccionamientoId);
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /bitacora/latest
   * Obtener última entrada de bitácora
   */
  router.get('/latest', 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 fraccionamientoId = req.query.fraccionamientoId as string;
      if (!fraccionamientoId) {
        res.status(400).json({ error: 'Bad Request', message: 'fraccionamientoId is required' });
        return;
      }

      const entry = await bitacoraService.findLatest(getContext(req), fraccionamientoId);
      if (!entry) {
        res.status(404).json({ error: 'Not Found', message: 'No log entries found' });
        return;
      }

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

  /**
   * GET /bitacora/:id
   * Obtener entrada por ID
   */
  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 entry = await bitacoraService.findById(getContext(req), req.params.id);
      if (!entry) {
        res.status(404).json({ error: 'Not Found', message: 'Log entry not found' });
        return;
      }

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

  /**
   * POST /bitacora
   * Crear entrada de bitácora
   */
  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: CreateBitacoraDto = req.body;

      if (!dto.fraccionamientoId || !dto.entryDate || !dto.description) {
        res.status(400).json({ error: 'Bad Request', message: 'fraccionamientoId, entryDate and description are required' });
        return;
      }

      const entry = await bitacoraService.createEntry(getContext(req), dto);
      res.status(201).json({ success: true, data: entry });
    } catch (error) {
      next(error);
    }
  });

  /**
   * PATCH /bitacora/:id
   * Actualizar entrada de bitácora
   */
  router.patch('/:id', 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: UpdateBitacoraDto = req.body;
      const entry = await bitacoraService.update(getContext(req), req.params.id, dto);

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

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

  /**
   * DELETE /bitacora/:id
   * Eliminar entrada de bitácora (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 bitacoraService.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Log entry not found' });
        return;
      }

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

  return router;
}

export default createBitacoraObraController;
