import { Request, Response } from 'express';
import { summaryService } from '@services/summary.service';
import { ResponseHandler } from '@utils/responseHandler';
import type { AuthenticatedRequest } from '../types/express';
import logger from '@utils/logger';

export class SummaryController {
  /**
   * Create a summary for a closed request
   * POST /api/v1/summaries
   * 
   * Access: Initiator or Admin/Management users
   * Body: { requestId: string, regenerate?: boolean }
   */
  async createSummary(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const userRole = (req as any).user?.role || (req as any).auth?.role;
      const { requestId, regenerate } = req.body;

      if (!requestId) {
        ResponseHandler.error(res, 'requestId is required', 400);
        return;
      }

      const summary = await summaryService.createSummary(requestId, userId, { 
        userRole, 
        regenerate: regenerate === true 
      });
      
      const message = regenerate ? 'Summary regenerated successfully' : 'Summary created successfully';
      ResponseHandler.success(res, summary, message, 201);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to create summary', 400, errorMessage);
    }
  }

  /**
   * Regenerate summary for a closed request (deletes existing and creates new)
   * POST /api/v1/summaries/:requestId/regenerate
   * 
   * Access: Initiator or Admin/Management users
   */
  async regenerateSummary(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const userRole = (req as any).user?.role || (req as any).auth?.role;
      const { requestId } = req.params;

      if (!requestId) {
        ResponseHandler.error(res, 'requestId is required', 400);
        return;
      }

      const summary = await summaryService.createSummary(requestId, userId, { 
        userRole, 
        regenerate: true 
      });
      
      ResponseHandler.success(res, summary, 'Summary regenerated successfully', 201);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to regenerate summary', 400, errorMessage);
    }
  }

  /**
   * Get summary details
   * GET /api/v1/summaries/:summaryId
   */
  async getSummaryDetails(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const { summaryId } = req.params;

      // The ID can be either a sharedSummaryId or a summaryId
      // Try shared summary first (for SharedSummaryDetail component)
      // If not found, try regular summary (for SummaryTab component)
      try {
        const summary = await summaryService.getSummaryDetailsBySharedId(summaryId, userId);
        ResponseHandler.success(res, summary, 'Summary retrieved successfully');
        return;
      } catch (sharedError: any) {
        // Only log error if it's not "not found" (other errors are real issues)
        if (!sharedError.message?.includes('not found')) {
          logger.error('[Summary] Error getting summary by shared ID:', sharedError);
        }
        
        // Try as regular summaryId (the service checks for both initiator and shared access)
        const summary = await summaryService.getSummaryDetails(summaryId, userId);
        ResponseHandler.success(res, summary, 'Summary retrieved successfully');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      const statusCode = errorMessage.includes('not found') ? 404 : 
                        errorMessage.includes('Access denied') ? 403 : 500;
      ResponseHandler.error(res, 'Failed to get summary details', statusCode, errorMessage);
    }
  }

  /**
   * Share summary with users
   * POST /api/v1/summaries/:summaryId/share
   */
  async shareSummary(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const { summaryId } = req.params;
      const { userIds } = req.body;

      if (!userIds || !Array.isArray(userIds) || userIds.length === 0) {
        ResponseHandler.error(res, 'userIds array is required', 400);
        return;
      }

      const sharedSummaries = await summaryService.shareSummary(summaryId, userId, userIds);
      ResponseHandler.success(res, sharedSummaries, 'Summary shared successfully', 201);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to share summary', 400, errorMessage);
    }
  }

  /**
   * Get list of users who received shared summary
   * GET /api/v1/summaries/:summaryId/recipients
   */
  async getSharedRecipients(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const { summaryId } = req.params;

      const recipients = await summaryService.getSharedRecipients(summaryId, userId);
      ResponseHandler.success(res, recipients, 'Shared recipients retrieved successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      const statusCode = errorMessage.includes('not found') || errorMessage.includes('Only the initiator') ? 404 : 500;
      ResponseHandler.error(res, 'Failed to get shared recipients', statusCode, errorMessage);
    }
  }

  /**
   * List summaries shared with current user
   * GET /api/v1/summaries/shared
   */
  async listSharedSummaries(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const page = Math.max(parseInt(String(req.query.page || '1'), 10), 1);
      const limit = Math.min(Math.max(parseInt(String(req.query.limit || '20'), 10), 1), 100);

      const result = await summaryService.listSharedSummaries(userId, page, limit);
      ResponseHandler.success(res, result, 'Shared summaries retrieved successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to list shared summaries', 500, errorMessage);
    }
  }

  /**
   * Mark shared summary as viewed
   * PATCH /api/v1/summaries/shared/:sharedSummaryId/view
   */
  async markAsViewed(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const { sharedSummaryId } = req.params;

      await summaryService.markAsViewed(sharedSummaryId, userId);
      ResponseHandler.success(res, null, 'Summary marked as viewed');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      const statusCode = errorMessage.includes('not found') || errorMessage.includes('Access denied') ? 404 : 500;
      ResponseHandler.error(res, 'Failed to mark summary as viewed', statusCode, errorMessage);
    }
  }

  /**
   * List summaries created by current user
   * GET /api/v1/summaries/my
   */
  async listMySummaries(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const page = Math.max(parseInt(String(req.query.page || '1'), 10), 1);
      const limit = Math.min(Math.max(parseInt(String(req.query.limit || '20'), 10), 1), 100);

      const result = await summaryService.listMySummaries(userId, page, limit);
      ResponseHandler.success(res, result, 'Summaries retrieved successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to list summaries', 500, errorMessage);
    }
  }

  /**
   * Get summary by requestId (checks if exists without creating)
   * GET /api/v1/summaries/request/:requestId
   */
  async getSummaryByRequestId(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const userId = (req as any).user?.userId || (req as any).user?.id || (req as any).auth?.userId;
      const { requestId } = req.params;

      if (!requestId) {
        ResponseHandler.error(res, 'requestId is required', 400);
        return;
      }

      const summary = await summaryService.getSummaryByRequestId(requestId, userId);
      if (summary) {
        ResponseHandler.success(res, summary, 'Summary retrieved successfully');
      } else {
        ResponseHandler.error(res, 'Summary not found', 404);
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to get summary', 500, errorMessage);
    }
  }
}

export const summaryController = new SummaryController();

