/**
 * UserProfileController - Controller de Perfiles de Usuario
 *
 * Endpoints REST para gestión de perfiles, herramientas y módulos.
 *
 * @module Profiles
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  UserProfileService,
  CreateUserProfileDto,
  UpdateUserProfileDto,
  ProfileFilters,
  AddToolDto,
  AddModuleDto,
} from '../services/user-profile.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';

interface ServiceContext {
  tenantId: string;
  userId?: string;
}

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

  // Services
  const profileService = new UserProfileService(dataSource);
  const userRepository = dataSource.getRepository(User);
  const tenantRepository = dataSource.getRepository(Tenant);
  const refreshTokenRepository = dataSource.getRepository(RefreshToken);
  const authService = new AuthService(userRepository, tenantRepository, refreshTokenRepository as any);
  const authMiddleware = new AuthMiddleware(authService, dataSource);

  // Helper to get 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,
    };
  };

  // ============ Profile CRUD ============

  /**
   * GET /profiles
   * List all profiles
   */
  router.get('/', authMiddleware.authenticate, 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 filters: ProfileFilters = {
        search: req.query.search as string,
        isSystem: req.query.isSystem === 'true' ? true : req.query.isSystem === 'false' ? false : undefined,
        page: parseInt(req.query.page as string) || 1,
        limit: Math.min(parseInt(req.query.limit as string) || 20, 100),
      };

      const result = await profileService.findAll(getContext(req), filters);

      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 /profiles/stats
   * Get profile statistics
   */
  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 profileService.getStats(getContext(req));
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /profiles/:id
   * Get profile by ID
   */
  router.get('/:id', authMiddleware.authenticate, 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 profile = await profileService.findById(getContext(req), req.params.id);
      if (!profile) {
        res.status(404).json({ error: 'Not Found', message: 'Profile not found' });
        return;
      }

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

  /**
   * GET /profiles/code/:code
   * Get profile by code
   */
  router.get('/code/:code', authMiddleware.authenticate, 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 profile = await profileService.findByCode(getContext(req), req.params.code);
      if (!profile) {
        res.status(404).json({ error: 'Not Found', message: 'Profile not found' });
        return;
      }

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

  /**
   * POST /profiles
   * Create new profile
   */
  router.post('/', 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 dto: CreateUserProfileDto = req.body;
      if (!dto.code || !dto.name) {
        res.status(400).json({ error: 'Bad Request', message: 'code and name are required' });
        return;
      }

      const profile = await profileService.create(getContext(req), dto);
      res.status(201).json({ success: true, data: profile });
    } catch (error) {
      if (error instanceof Error && error.message.includes('already exists')) {
        res.status(409).json({ error: 'Conflict', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * PUT /profiles/:id
   * Update profile
   */
  router.put('/: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 dto: UpdateUserProfileDto = req.body;
      const profile = await profileService.update(getContext(req), req.params.id, dto);

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

      res.status(200).json({ success: true, data: profile });
    } catch (error) {
      if (error instanceof Error && error.message.includes('system profiles')) {
        res.status(403).json({ error: 'Forbidden', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * DELETE /profiles/:id
   * Delete profile
   */
  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 profileService.delete(getContext(req), req.params.id);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Profile not found' });
        return;
      }

      res.status(200).json({ success: true, message: 'Profile deleted' });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('system profiles')) {
          res.status(403).json({ error: 'Forbidden', message: error.message });
          return;
        }
        if (error.message.includes('active assignments')) {
          res.status(409).json({ error: 'Conflict', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * POST /profiles/:id/clone
   * Clone a profile
   */
  router.post('/:id/clone', 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 { code, name } = req.body;
      if (!code || !name) {
        res.status(400).json({ error: 'Bad Request', message: 'code and name are required for cloning' });
        return;
      }

      const profile = await profileService.cloneProfile(getContext(req), req.params.id, code, name);
      res.status(201).json({ success: true, data: profile });
    } catch (error) {
      if (error instanceof Error && error.message.includes('already exists')) {
        res.status(409).json({ error: 'Conflict', message: error.message });
        return;
      }
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  // ============ Tools Management ============

  /**
   * GET /profiles/:id/tools
   * Get profile tools
   */
  router.get('/:id/tools', authMiddleware.authenticate, 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 tools = await profileService.getTools(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: tools });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /profiles/:id/tools
   * Add tool to profile
   */
  router.post('/:id/tools', 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 dto: AddToolDto = req.body;
      if (!dto.toolCode || !dto.toolName) {
        res.status(400).json({ error: 'Bad Request', message: 'toolCode and toolName are required' });
        return;
      }

      const tool = await profileService.addTool(getContext(req), req.params.id, dto);
      res.status(201).json({ success: true, data: tool });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('not found')) {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message.includes('already assigned')) {
          res.status(409).json({ error: 'Conflict', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * PUT /profiles/:id/tools/:toolId
   * Update tool
   */
  router.put('/:id/tools/:toolId', 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 tool = await profileService.updateTool(getContext(req), req.params.id, req.params.toolId, req.body);
      if (!tool) {
        res.status(404).json({ error: 'Not Found', message: 'Tool not found' });
        return;
      }

      res.status(200).json({ success: true, data: tool });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * DELETE /profiles/:id/tools/:toolId
   * Remove tool from profile
   */
  router.delete('/:id/tools/:toolId', 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 deleted = await profileService.removeTool(getContext(req), req.params.id, req.params.toolId);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Tool not found' });
        return;
      }

      res.status(200).json({ success: true, message: 'Tool removed' });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  // ============ Modules Management ============

  /**
   * GET /profiles/:id/modules
   * Get profile modules
   */
  router.get('/:id/modules', authMiddleware.authenticate, 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 modules = await profileService.getModules(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: modules });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /profiles/:id/modules
   * Add module to profile
   */
  router.post('/:id/modules', 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 dto: AddModuleDto = req.body;
      if (!dto.moduleCode) {
        res.status(400).json({ error: 'Bad Request', message: 'moduleCode is required' });
        return;
      }

      const module = await profileService.addModule(getContext(req), req.params.id, dto);
      res.status(201).json({ success: true, data: module });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('not found')) {
          res.status(404).json({ error: 'Not Found', message: error.message });
          return;
        }
        if (error.message.includes('already assigned')) {
          res.status(409).json({ error: 'Conflict', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * PUT /profiles/:id/modules/:moduleId
   * Update module
   */
  router.put('/:id/modules/:moduleId', 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 module = await profileService.updateModule(getContext(req), req.params.id, req.params.moduleId, req.body);
      if (!module) {
        res.status(404).json({ error: 'Not Found', message: 'Module not found' });
        return;
      }

      res.status(200).json({ success: true, data: module });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * DELETE /profiles/:id/modules/:moduleId
   * Remove module from profile
   */
  router.delete('/:id/modules/:moduleId', 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 deleted = await profileService.removeModule(getContext(req), req.params.id, req.params.moduleId);
      if (!deleted) {
        res.status(404).json({ error: 'Not Found', message: 'Module not found' });
        return;
      }

      res.status(200).json({ success: true, message: 'Module removed' });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  // ============ User Assignments ============

  /**
   * GET /profiles/:id/users
   * Get users assigned to profile
   */
  router.get('/:id/users', 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 assignments = await profileService.getProfileUsers(getContext(req), req.params.id);
      res.status(200).json({ success: true, data: assignments });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * POST /profiles/:id/users/:userId
   * Assign profile to user
   */
  router.post('/:id/users/:userId', 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 { isPrimary, expiresAt } = req.body;
      const assignment = await profileService.assignToUser(
        getContext(req),
        req.params.id,
        req.params.userId,
        { isPrimary, expiresAt: expiresAt ? new Date(expiresAt) : undefined }
      );

      res.status(200).json({ success: true, data: assignment });
    } catch (error) {
      if (error instanceof Error && error.message.includes('not found')) {
        res.status(404).json({ error: 'Not Found', message: error.message });
        return;
      }
      next(error);
    }
  });

  /**
   * DELETE /profiles/:id/users/:userId
   * Remove profile from user
   */
  router.delete('/:id/users/:userId', 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 removed = await profileService.removeFromUser(getContext(req), req.params.id, req.params.userId);
      if (!removed) {
        res.status(404).json({ error: 'Not Found', message: 'Assignment not found' });
        return;
      }

      res.status(200).json({ success: true, message: 'Profile removed from user' });
    } catch (error) {
      next(error);
    }
  });

  return router;
}

export default createUserProfileController;
