/**
 * PersonController - Controller de Personas
 *
 * Endpoints REST para gestión de personas/contactos.
 *
 * @module Profiles
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import {
  PersonService,
  CreatePersonDto,
  UpdatePersonDto,
  PersonFilters,
} from '../services/person.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 createPersonController(dataSource: DataSource): Router {
  const router = Router();

  // Services
  const personService = new PersonService(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,
    };
  };

  /**
   * GET /persons
   * List all persons
   */
  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: PersonFilters = {
        search: req.query.search as string,
        isVerified: req.query.isVerified === 'true' ? true : req.query.isVerified === 'false' ? false : undefined,
        isResponsibleForTenant: req.query.isResponsible === 'true' ? true : req.query.isResponsible === '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 personService.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 /persons/stats
   * Get person 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 personService.getStats();
      res.status(200).json({ success: true, data: stats });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /persons/responsibles
   * Get tenant responsibles
   */
  router.get('/responsibles', 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 responsibles = await personService.getTenantResponsibles();
      res.status(200).json({ success: true, data: responsibles });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /persons/expiring-ids
   * Get persons with expiring identification
   */
  router.get('/expiring-ids', 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 daysAhead = parseInt(req.query.days as string) || 30;
      const persons = await personService.getExpiringIdentifications(daysAhead);
      res.status(200).json({ success: true, data: persons });
    } catch (error) {
      next(error);
    }
  });

  /**
   * GET /persons/:id
   * Get person 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 person = await personService.findById(req.params.id);
      if (!person) {
        res.status(404).json({ error: 'Not Found', message: 'Person not found' });
        return;
      }

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

  /**
   * GET /persons/email/:email
   * Get person by email
   */
  router.get('/email/:email', 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 person = await personService.findByEmail(req.params.email);
      if (!person) {
        res.status(404).json({ error: 'Not Found', message: 'Person not found' });
        return;
      }

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

  /**
   * POST /persons
   * Create new person
   */
  router.post('/', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'manager'), 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: CreatePersonDto = req.body;
      if (!dto.fullName || !dto.email) {
        res.status(400).json({ error: 'Bad Request', message: 'fullName and email are required' });
        return;
      }

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

  /**
   * PUT /persons/:id
   * Update person
   */
  router.put('/:id', authMiddleware.authenticate, authMiddleware.authorize('admin', 'director', 'manager'), 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: UpdatePersonDto = req.body;
      const person = await personService.update(req.params.id, dto);

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

      res.status(200).json({ success: true, data: person });
    } catch (error) {
      if (error instanceof Error && error.message.includes('already in use')) {
        res.status(409).json({ error: 'Conflict', message: error.message });
        return;
      }
      next(error);
    }
  });

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

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

  /**
   * POST /persons/:id/verify
   * Verify person identity
   */
  router.post('/:id/verify', 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 person = await personService.verify(getContext(req), req.params.id);
      if (!person) {
        res.status(404).json({ error: 'Not Found', message: 'Person not found' });
        return;
      }

      res.status(200).json({ success: true, data: person });
    } catch (error) {
      if (error instanceof Error) {
        if (error.message.includes('already verified')) {
          res.status(409).json({ error: 'Conflict', message: error.message });
          return;
        }
        if (error.message.includes('required for verification')) {
          res.status(400).json({ error: 'Bad Request', message: error.message });
          return;
        }
      }
      next(error);
    }
  });

  /**
   * POST /persons/:id/revoke-verification
   * Revoke person verification
   */
  router.post('/:id/revoke-verification', 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 person = await personService.revokeVerification(req.params.id);
      if (!person) {
        res.status(404).json({ error: 'Not Found', message: 'Person not found' });
        return;
      }

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

  /**
   * PUT /persons/:id/responsible
   * Set/unset as tenant responsible
   */
  router.put('/:id/responsible', 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 { isResponsible } = req.body;
      if (isResponsible === undefined) {
        res.status(400).json({ error: 'Bad Request', message: 'isResponsible is required' });
        return;
      }

      const person = await personService.setAsTenantResponsible(req.params.id, isResponsible);
      if (!person) {
        res.status(404).json({ error: 'Not Found', message: 'Person not found' });
        return;
      }

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

  return router;
}

export default createPersonController;
