/**
 * BackupController - Controller de Backups
 *
 * Endpoints REST para gestión de backups del sistema.
 *
 * @module Admin
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { BackupService, CreateBackupDto, BackupFilters } from '../services/backup.service';
import { AuthMiddleware } from '../../auth/middleware/auth.middleware';
import { AuthService } from '../../auth/services/auth.service';
import { Backup } from '../entities/backup.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 createBackupController(dataSource: DataSource): Router {
  const router = Router();

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

  // Servicios
  const backupService = new BackupService(backupRepository);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

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

  /**
   * GET /backups
   */
  router.get('/', 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 page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 100);

      const filters: BackupFilters = {};
      if (req.query.backupType) filters.backupType = req.query.backupType as any;
      if (req.query.status) filters.status = req.query.status as any;
      if (req.query.storageLocation) filters.storageLocation = req.query.storageLocation as any;
      if (req.query.isScheduled !== undefined) filters.isScheduled = req.query.isScheduled === 'true';
      if (req.query.isVerified !== undefined) filters.isVerified = req.query.isVerified === 'true';
      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 result = await backupService.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 /backups/stats
   */
  router.get('/stats', 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 stats = await backupService.getStats(getContext(req));
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /backups/last
   */
  router.get('/last', 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 backupType = req.query.backupType as any;
      const backup = await backupService.getLastSuccessful(getContext(req), backupType);

      if (!backup) {
        res.status(404).json({ error: 'Not Found', message: 'No successful backup found' });
        return;
      }

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

  /**
   * GET /backups/pending-verification
   */
  router.get('/pending-verification', 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 backups = await backupService.getPendingVerification(getContext(req));
      res.status(200).json({ success: true, data: backups });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /backups/:id
   */
  router.get('/: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 backup = await backupService.findById(getContext(req), req.params.id);
      if (!backup) {
        res.status(404).json({ error: 'Not Found', message: 'Backup not found' });
        return;
      }

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

  /**
   * POST /backups
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin'), 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: CreateBackupDto = req.body;
      if (!dto.backupType || !dto.name) {
        res.status(400).json({
          error: 'Bad Request',
          message: 'backupType and name are required',
        });
        return;
      }

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

  /**
   * POST /backups/:id/verify
   */
  router.post('/:id/verify', authMiddleware.authenticate, authMiddleware.authorize('admin'), 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 backup = await backupService.markVerified(getContext(req), req.params.id);
      if (!backup) {
        res.status(404).json({ error: 'Not Found', message: 'Backup not found' });
        return;
      }

      res.status(200).json({ success: true, data: backup });
    } catch (error) {
      if (error instanceof Error && error.message.includes('Only completed')) {
        res.status(400).json({ error: 'Bad Request', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /backups/:id/cancel
   */
  router.post('/:id/cancel', authMiddleware.authenticate, authMiddleware.authorize('admin'), 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 backup = await backupService.cancelBackup(getContext(req), req.params.id);
      if (!backup) {
        res.status(404).json({ error: 'Not Found', message: 'Backup not found' });
        return;
      }

      res.status(200).json({ success: true, data: backup });
    } catch (error) {
      if (error instanceof Error && error.message.includes('Only pending')) {
        res.status(400).json({ error: 'Bad Request', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /backups/cleanup
   */
  router.post('/cleanup', authMiddleware.authenticate, authMiddleware.authorize('admin'), 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 expired = await backupService.cleanupExpired(getContext(req));
      res.status(200).json({
        success: true,
        message: `Marked ${expired} backups as expired`,
        data: { expired },
      });
    } catch (error) {
      next(error);
    }
  });

  /**
   * DELETE /backups/:id
   */
  router.delete('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin'), 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 deleted = await backupService.softDelete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Backup not found' });
        return;
      }

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

  return router;
}

export default createBackupController;
