import { Request, Response } from 'express';
import UserModel from '../../models/User';
import { UniResponse } from '../../lib/UniResponse';
import { StatusCode } from '../../lib/StatusCode';
import QRCodeModel from '../../models/QrCode';
import ScanModel from '../../models/Scan';
import MediaModel from '../../models/MediaSchema';
import MessageModel from '../../models/Messages';
import ConversationModel from '../../models/Conversation';
import { asyncHandler } from '../../utils/asyncHandler';
import { AdminValidation, ValidationUtils } from '../../validations';
import { MedicalEncryption } from '../../utils/medicalEncryption';
import { AdminRepository } from './index.repository';
import fs from 'fs';
import path from 'path';
import LoggingModel from '../../models/Logging';
import ContactModel from '../../models/Contact';
import PDFDocument from 'pdfkit';
import { existsSync, readFileSync } from 'fs';
import { resolve } from 'path';
import jsPDF from 'jspdf';
import { autoTable } from 'jspdf-autotable';
import { Types } from 'mongoose';
import { NotificationService } from '../notification/NotificationService';
import { humanizeClientError } from '../../utils/humanReadableError';

export class AdminController {
  // ============== GET ALL USERS =================
  public static getAllUsers = asyncHandler(async (req: Request, res: Response) => {
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 10;
    const search = (req.query.search as string) || '';
    const skip = (page - 1) * limit;

    // Build filter object - exclude ADMIN users
    const filter: any = { is_delete: false, role: { $ne: 'ADMIN' } };

    // Add search functionality
    if (search) {
      filter.$or = [
        { email: { $regex: search, $options: 'i' } },
        { first_name: { $regex: search, $options: 'i' } },
        { last_name: { $regex: search, $options: 'i' } },
        { phone_number: { $regex: search, $options: 'i' } },
      ];
    }

    const totalUsers = await UserModel.countDocuments(filter);

    const users = await UserModel.find(filter)
      .select('-password')
      .select('-fcmTokens')
      .skip(skip)
      .limit(limit)
      .sort({ createdAt: -1 });

    const totalPages = Math.ceil(totalUsers / limit);
    const hasNextPage = page < totalPages;
    const hasPrevPage = page > 1;

    const paginationData = {
      users,
      pagination: {
        currentPage: page,
        totalPages,
        totalUsers,
        limit,
        hasNextPage,
        hasPrevPage,
      },
    };

    return res.json(
      UniResponse.Success(
        StatusCode.getReasonPhrase(StatusCode.OK),
        paginationData,
        200
      )
    );
  });

  // ========= GET ANAYLYTICS ===============
  public static getAnalytics = asyncHandler(async (req: Request, res: Response) => {
    const startTime = Date.now();
    const requestId = Math.random().toString(36).substring(7);

    console.log(`🔍 [${requestId}] GET_ANALYTICS_STARTED`, {
      timestamp: new Date().toISOString(),
      method: req.method,
      url: req.url,
      userAgent: req.get('User-Agent'),
      clientIP: req.ip,
      query: req.query,
      params: req.params,
    });

    // 1. Date Boundary Calculation (hardcoded to 7 days)
    const now = new Date();
    const endDate = new Date(now);
    endDate.setHours(23, 59, 59, 999);

    const startDate = new Date(now);
    startDate.setDate(now.getDate() - 6); // 6 days ago + today = 7 days
    startDate.setHours(0, 0, 0, 0);

    console.log(`📅 [${requestId}] DATE_RANGE_CALCULATED`, {
      now: now.toISOString(),
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString(),
    });

    // Generate labels for the last 7 days and their corresponding date keys
    const labels: string[] = [];
    const dateKeys: string[] = [];
    for (let i = 6; i >= 0; i--) {
      const date = new Date(now);
      date.setDate(now.getDate() - i);
      labels.push(date.toLocaleDateString('en-US', { weekday: 'short' }));
      dateKeys.push(this.toISODate(date) || '');
    }

    console.log(`🏷️ [${requestId}] LABELS_GENERATED`, {
      labels: labels,
      dateKeys: dateKeys,
    });

    console.time(`⏱️ [${requestId}] TOTAL_COUNTS_DURATION`);
    try {
      // 3. Totals (within the date range)
      // Support both createdAt and created_at naming by using $or
      const dateMatch = {
        $or: [
          { createdAt: { $gte: startDate, $lte: endDate } },
          { created_at: { $gte: startDate, $lte: endDate } },
        ],
      };

      console.log(`📊 [${requestId}] COUNTING_TOTALS`, { dateMatch });

      const totalUsers = await UserModel.countDocuments({
        // isProfileComplete: true,
        is_delete: false,
        ...dateMatch,
      });
      console.log(`👥 [${requestId}] USERS_COUNT_RETRIEVED (in range)`, { totalUsers });

      const totalQrCodes = await QRCodeModel.countDocuments({
        status: 'ACTIVE',
        ...dateMatch,
      });
      console.log(`📱 [${requestId}] QRCODES_COUNT_RETRIEVED (in range)`, {
        totalQrCodes,
      });

      const mediaCount = await MediaModel.countDocuments({
        ...dateMatch,
      });
      console.log(`🖼️ [${requestId}] MEDIA_COUNT_RETRIEVED (in range)`, { mediaCount });

      console.timeEnd(`⏱️ [${requestId}] TOTAL_COUNTS_DURATION`);

      // 4. Dynamic Breakdown Generation (aggregate per-day for users, qrcodes, and scans)
      console.time(`⏱️ [${requestId}] DAILY_ANALYTICS_DURATION`);

      console.log(`🔍 [${requestId}] STARTING_USER_AGGREGATION`, {
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString(),
      });

      // Aggregate users per day (coalesce createdAt/created_at)
      const usersAgg = await UserModel.aggregate([
        {
          $match: {
            isProfileComplete: true,
            is_delete: false,
            $or: [
              { createdAt: { $gte: startDate, $lte: endDate } },
              { created_at: { $gte: startDate, $lte: endDate } },
            ],
          },
        },
        {
          $addFields: {
            createdAt_coalesced: { $ifNull: ['$createdAt', '$created_at'] },
          },
        },
        {
          $group: {
            _id: {
              $dateToString: { format: '%Y-%m-%d', date: '$createdAt_coalesced' },
            },
            count: { $sum: 1 },
          },
        },
      ]);

      console.log(`📊 [${requestId}] USER_AGGREGATION_RESULT`, {
        rawResult: usersAgg,
        resultCount: usersAgg.length,
      });

      console.log(`🔍 [${requestId}] STARTING_QRCODE_AGGREGATION`, {
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString(),
      });

      // Aggregate qrcodes per day
      const qrAgg = await QRCodeModel.aggregate([
        {
          $match: {
            status: 'ACTIVE',
            $or: [
              { createdAt: { $gte: startDate, $lte: endDate } },
              { created_at: { $gte: startDate, $lte: endDate } },
            ],
          },
        },
        {
          $addFields: {
            createdAt_coalesced: { $ifNull: ['$createdAt', '$created_at'] },
          },
        },
        {
          $group: {
            _id: {
              $dateToString: { format: '%Y-%m-%d', date: '$createdAt_coalesced' },
            },
            count: { $sum: 1 },
          },
        },
      ]);

      console.log(`📊 [${requestId}] QRCODE_AGGREGATION_RESULT`, {
        rawResult: qrAgg,
        resultCount: qrAgg.length,
      });

      console.log(`🔍 [${requestId}] STARTING_SCAN_AGGREGATION`, {
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString(),
      });

      // Aggregate scans per day
      const scanAgg = await ScanModel.aggregate([
        {
          $match: {
            createdAt: { $gte: startDate, $lte: endDate },
          },
        },
        {
          $group: {
            _id: {
              $dateToString: { format: '%Y-%m-%d', date: '$createdAt' },
            },
            count: { $sum: 1 },
          },
        },
      ]);

      console.log(`📊 [${requestId}] SCAN_AGGREGATION_RESULT`, {
        rawResult: scanAgg,
        resultCount: scanAgg.length,
      });

      // Turn aggregation results into lookup maps keyed by 'YYYY-MM-DD'
      const usersByDate = new Map<string, number>();
      usersAgg.forEach((r: any) => usersByDate.set(r._id, r.count));

      const qrsByDate = new Map<string, number>();
      qrAgg.forEach((r: any) => qrsByDate.set(r._id, r.count));

      const scansByDate = new Map<string, number>();
      scanAgg.forEach((r: any) => scansByDate.set(r._id, r.count));

      console.log(`🗺️ [${requestId}] LOOKUP_MAPS_CREATED`, {
        usersByDate: Object.fromEntries(usersByDate),
        qrsByDate: Object.fromEntries(qrsByDate),
        scansByDate: Object.fromEntries(scansByDate),
      });

      // Build dailyAnalytics matched to labels
      // Use dateKeys if available for exact date matching, otherwise use labels
      const dailyAnalytics = labels.map((label: string, index: number) => {
        // Use the corresponding date key if available, otherwise try to convert the label
        const dateKey =
          dateKeys && index < dateKeys.length
            ? dateKeys[index]
            : this.toISODate(label) || label;

        const usersCount = usersByDate.get(String(dateKey || '')) || 0;
        const qrcodesCount = qrsByDate.get(String(dateKey || '')) || 0;
        const scansCount = scansByDate.get(String(dateKey || '')) || 0;

        console.log(`📈 [${requestId}] DAILY_ANALYTICS_MAPPING`, {
          index,
          label,
          dateKey,
          usersCount,
          qrcodesCount,
          scansCount,
        });

        return {
          name: label,
          scans: scansCount,
          users: usersCount,
          qrcodes: qrcodesCount,
        };
      });

      console.timeEnd(`⏱️ [${requestId}] DAILY_ANALYTICS_DURATION`);

      // 5. Response
      const response = {
        // totals within the requested range
        totalUsers,
        totalQrCodes,
        mediaCount,
        WeeklyAnalytics: dailyAnalytics,
        meta: {
          range: { startDate: startDate.toISOString(), endDate: endDate.toISOString() },
          labelsCount: labels.length,
          period: '7d',
        },
      };

      console.log(`📦 [${requestId}] RESPONSE_BUILT`, {
        responseSummary: {
          totalUsers,
          totalQrCodes,
          mediaCount,
          weeklyAnalyticsCount: dailyAnalytics.length,
          meta: response.meta,
        },
      });

      const duration = Date.now() - startTime;
      console.log(`✅ [${requestId}] ANALYTICS_API_COMPLETED`, {
        duration: `${duration}ms`,
        status: 'SUCCESS',
        responseSize: JSON.stringify(response).length,
      });

      return res.send(
        UniResponse.Success(StatusCode.getReasonPhrase(StatusCode.OK), response, 200)
      );
    } catch (err) {
      const duration = Date.now() - startTime;
      console.error(`❌ [${requestId}] ANALYTICS_API_ERROR`, {
        duration: `${duration}ms`,
        error:
          err instanceof Error
            ? {
                name: err.name,
                message: err.message,
                stack: err.stack,
              }
            : err,
      });
      return res
        .status(500)
        .json(
          UniResponse.Error(
            'Failed to compute analytics',
            humanizeClientError(
              err,
              'We could not compute analytics right now. Please try again.'
            ),
            500
          )
        );
    }
  });

  // ======== DELETE USER ======================
  public static DeleteUser = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    console.log(id);

    // Check if user exists and is not already deleted
    const user = await UserModel.findOne({ _id: id });

    console.log(user);

    if (!user) {
      return res.json(
        UniResponse.Error('User not found or already deleted', StatusCode.NOT_FOUND)
      );
    }

    // Soft delete the user by setting is_delete to true
    await UserModel.findByIdAndUpdate(id as any, { is_delete: true }, { new: true });

    return res.json(
      UniResponse.Success('User deleted successfully', null, StatusCode.OK)
    );
  });

  public static ChangeUserStatus = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    // Check if user exists
    const user = await UserModel.findOne({ _id: id });

    if (!user) {
      return res.json(UniResponse.Error('User not found', StatusCode.NOT_FOUND));
    }

    // Update user status
    const updatedUser = await UserModel.findByIdAndUpdate(
      id,
      {
        status:
          user?.status?.toUpperCase()?.trim() === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE',
      },
      { new: true }
    ).select('-password');

    console.log(`============== UPDATED USER =================`);
    console.log(updatedUser);
    console.log(`============== UPDATED USER =================`);

    return res.json(
      UniResponse.Success(
        'User status updated successfully',
        {
          user: updatedUser,
          previousStatus: user.status,
          newStatus:
            user?.status?.toUpperCase()?.trim() === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE',
        },
        StatusCode.OK
      )
    );
  });

  // ============== GET ALL MEDIA =================
  public static getAllMedia = asyncHandler(async (req: Request, res: Response) => {
    // Validate query parameters
    const validationResult = AdminValidation.validateGetAllMediaQuery(req.query);
    if (!ValidationUtils.isValidationSuccess(validationResult)) {
      return res.json(
        UniResponse.Error(
          ValidationUtils.formatValidationError(validationResult.error),
          400
        )
      );
    }

    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 10;
    const skip = (page - 1) * limit;

    const totalMedia = await MediaModel.countDocuments({});

    // Get all media with owner information through aggregation
    const mediaWithOwners = await MediaModel.aggregate([
      {
        $lookup: {
          from: 'qrcodes',
          localField: '_id',
          foreignField: 'images',
          as: 'qrCodeUsage',
          pipeline: [
            {
              $lookup: {
                from: 'users',
                localField: 'created_by',
                foreignField: '_id',
                as: 'owner',
                pipeline: [
                  {
                    $project: {
                      name: 1,
                      first_name: 1,
                      last_name: 1,
                      email: 1,
                      profile_picture: 1,
                    },
                  },
                ],
              },
            },
            {
              $addFields: {
                owner: { $arrayElemAt: ['$owner', 0] },
              },
            },
            { $project: { title: 1, type: 1, created_at: 1, owner: 1 } },
          ],
        },
      },
      {
        $lookup: {
          from: 'users',
          localField: '_id',
          foreignField: 'media_id',
          as: 'profileUsage',
          pipeline: [
            {
              $project: {
                name: 1,
                first_name: 1,
                last_name: 1,
                email: 1,
                profile_picture: 1,
              },
            },
          ],
        },
      },
      {
        $addFields: {
          // Calculate time since last modification
          timeAgo: {
            $let: {
              vars: {
                diffInMs: { $subtract: [new Date(), '$updatedAt'] },
              },
              in: {
                $switch: {
                  branches: [
                    {
                      case: { $lt: ['$$diffInMs', 60000] }, // Less than 1 minute
                      then: 'Just now',
                    },
                    {
                      case: { $lt: ['$$diffInMs', 3600000] }, // Less than 1 hour
                      then: {
                        $concat: [
                          { $toString: { $floor: { $divide: ['$$diffInMs', 60000] } } },
                          ' min ago',
                        ],
                      },
                    },
                    {
                      case: { $lt: ['$$diffInMs', 86400000] }, // Less than 1 day
                      then: {
                        $concat: [
                          {
                            $toString: { $floor: { $divide: ['$$diffInMs', 3600000] } },
                          },
                          ' hour',
                          {
                            $cond: [
                              {
                                $eq: [
                                  { $floor: { $divide: ['$$diffInMs', 3600000] } },
                                  1,
                                ],
                              },
                              '',
                              's',
                            ],
                          },
                          ' ago',
                        ],
                      },
                    },
                    {
                      case: { $lt: ['$$diffInMs', 2592000000] }, // Less than 30 days
                      then: {
                        $concat: [
                          {
                            $toString: {
                              $floor: { $divide: ['$$diffInMs', 86400000] },
                            },
                          },
                          ' day',
                          {
                            $cond: [
                              {
                                $eq: [
                                  { $floor: { $divide: ['$$diffInMs', 86400000] } },
                                  1,
                                ],
                              },
                              '',
                              's',
                            ],
                          },
                          ' ago',
                        ],
                      },
                    },
                  ],
                  default: {
                    $concat: [
                      {
                        $toString: { $floor: { $divide: ['$$diffInMs', 2592000000] } },
                      },
                      ' month',
                      {
                        $cond: [
                          {
                            $eq: [
                              { $floor: { $divide: ['$$diffInMs', 2592000000] } },
                              1,
                            ],
                          },
                          '',
                          's',
                        ],
                      },
                      ' ago',
                    ],
                  },
                },
              },
            },
          },
          // Determine primary owner and usage type
          primaryOwner: {
            $cond: [
              { $gt: [{ $size: '$profileUsage' }, 0] },
              { $arrayElemAt: ['$profileUsage', 0] },
              {
                $cond: [
                  { $gt: [{ $size: '$qrCodeUsage' }, 0] },
                  { $arrayElemAt: ['$qrCodeUsage.owner', 0] },
                  null,
                ],
              },
            ],
          },
          usageType: {
            $cond: [
              { $gt: [{ $size: '$profileUsage' }, 0] },
              'Profile Picture',
              {
                $cond: [
                  { $gt: [{ $size: '$qrCodeUsage' }, 0] },
                  'QR Code Image',
                  'Orphaned',
                ],
              },
            ],
          },
          usageCount: {
            $add: [{ $size: '$profileUsage' }, { $size: '$qrCodeUsage' }],
          },
        },
      },
      {
        $project: {
          originalName: 1,
          filePath: 1,
          mimeType: 1,
          size: 1,
          createdAt: 1,
          updatedAt: 1,
          timeAgo: 1,
          primaryOwner: 1,
          usageType: 1,
          usageCount: 1,
          qrCodeUsage: {
            $map: {
              input: '$qrCodeUsage',
              as: 'qr',
              in: {
                title: '$$qr.title',
                type: '$$qr.type',
                created_at: '$$qr.created_at',
              },
            },
          },
        },
      },
      { $sort: { updatedAt: -1 } },
      { $skip: skip },
      { $limit: limit },
    ]);

    const totalPages = Math.ceil(totalMedia / limit);
    const hasNextPage = page < totalPages;
    const hasPrevPage = page > 1;

    const paginationData = {
      media: mediaWithOwners,
      pagination: {
        currentPage: page,
        totalPages,
        totalMedia,
        limit,
        hasNextPage,
        hasPrevPage,
      },
    };

    return res.json(
      UniResponse.Success(
        StatusCode.getReasonPhrase(StatusCode.OK),
        paginationData,
        200
      )
    );
  });

  // ============== GET ALL QR CODES =================
  public static getAllQrCodes = asyncHandler(async (req: Request, res: Response) => {
    // Validate query parameters (only search and pagination)
    const validationResult = AdminValidation.validateGetAllQrCodesQuery(req.query);
    if (!ValidationUtils.isValidationSuccess(validationResult)) {
      return res.json(
        UniResponse.Error(
          ValidationUtils.formatValidationError(validationResult.error),
          400
        )
      );
    }

    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 10;
    const search = req.query.search as string;
    const sortBy = (req.query.sortBy as string) || 'date';
    const sortOrder = (req.query.sortOrder as string) || 'desc';

    // Build filter object - only basic filter and search
    const filter: any = { isDelete: false };

    // Add search functionality
    if (search) {
      filter.$text = { $search: search };
    }

    // Build sort object
    let sortObj: any = {};
    switch (sortBy) {
      case 'name':
        sortObj = { title: sortOrder === 'asc' ? 1 : -1 };
        break;
      case 'scans':
        sortObj = { scansCount: sortOrder === 'asc' ? 1 : -1 };
        break;
      case 'date':
      default:
        sortObj = { created_at: sortOrder === 'asc' ? 1 : -1 };
        break;
    }

    // Build aggregation pipeline
    const aggregationPipeline: any[] = [
      { $match: filter },
      {
        $lookup: {
          from: 'scans',
          localField: '_id',
          foreignField: 'qrcode_id',
          as: 'scans',
        },
      },
      {
        $lookup: {
          from: 'qrcode_uploads',
          localField: '_id',
          foreignField: 'qrcode_id',
          as: 'qrcode_uploads',
        },
      },
      {
        $lookup: {
          from: 'media',
          localField: 'qrcode_uploads.media_id',
          foreignField: '_id',
          as: 'qrcode_media',
        },
      },
      {
        $lookup: {
          from: 'users',
          localField: 'created_by',
          foreignField: '_id',
          as: 'created_by',
          pipeline: [{ $project: { name: 1, email: 1, profile_picture: 1 } }],
        },
      },
      {
        $lookup: {
          from: 'media',
          localField: 'images',
          foreignField: '_id',
          as: 'images',
          pipeline: [{ $project: { filename: 1, url: 1 } }],
        },
      },
      {
        $lookup: {
          from: 'locations',
          localField: 'location',
          foreignField: '_id',
          as: 'location',
          pipeline: [{ $project: { address: 1, latitude: 1, longitude: 1 } }],
        },
      },
      {
        $addFields: {
          created_by: { $arrayElemAt: ['$created_by', 0] },
          location: { $arrayElemAt: ['$location', 0] },
          scansCount: { $size: '$scans' },
          qr_code_url: {
            $cond: {
              if: { $gt: [{ $size: '$qrcode_media' }, 0] },
              then: { $arrayElemAt: ['$qrcode_media.filePath', 0] },
              else: null,
            },
          },
        },
      },
      {
        $project: {
          scans: 0,
          qrcode_uploads: 0,
          qrcode_media: 0,
        },
      },
      { $sort: sortObj },
    ];

    // Use mongoose-paginate-v2 with aggregation
    const aggregate = QRCodeModel.aggregate(aggregationPipeline);
    const paginationResult = await (QRCodeModel as any).aggregatePaginate(aggregate, {
      page,
      limit,
    });

    // Decrypt medical data for MEDICAL_QR types and format QR code URL
    const processedQrCodes = paginationResult.docs.map((qrcode: any) => {
      if (
        qrcode.type === 'MEDICAL_QR' &&
        qrcode.type_details &&
        typeof qrcode.type_details === 'string' &&
        MedicalEncryption.isEncrypted(qrcode.type_details)
      ) {
        try {
          qrcode.type_details = MedicalEncryption.decryptMedicalData(
            qrcode.type_details
          );
        } catch (error) {
          console.error('Error decrypting medical data in admin controller:', error);
          // Keep encrypted data if decryption fails
        }
      }

      // Format QR code URL to match the pattern used elsewhere
      if (qrcode.qr_code_url) {
        // Remove leading slashes and add a single leading slash
        qrcode.qr_code_url = `${qrcode.qr_code_url.replace(/^\/+/, '')}`;
      }

      return qrcode;
    });

    const paginationData = {
      qrCodes: processedQrCodes,
      pagination: {
        currentPage: paginationResult.page,
        totalPages: paginationResult.totalPages,
        totalQrCodes: paginationResult.totalDocs,
        limit: paginationResult.limit,
        hasNextPage: paginationResult.hasNextPage,
        hasPrevPage: paginationResult.hasPrevPage,
      },
    };

    return res.json(
      UniResponse.Success(
        StatusCode.getReasonPhrase(StatusCode.OK),
        paginationData,
        200
      )
    );
  });

  // ============== DELETE QR CODE (SOFT DELETE) =================
  public static deleteQrCode = asyncHandler(async (req: Request, res: Response) => {
    const { id } = req.params;

    // Validate QR code ID
    if (!Types.ObjectId.isValid(id as any)) {
      return res.json(UniResponse.Error('Invalid QR code ID', StatusCode.BAD_REQUEST));
    }

    // Check if QR code exists and is not already deleted
    const qrCode = await QRCodeModel.findOne({
      _id: new Types.ObjectId(id as any),
      isDelete: false,
    });

    if (!qrCode) {
      return res.json(
        UniResponse.Error('QR code not found or already deleted', StatusCode.NOT_FOUND)
      );
    }

    // Soft delete the QR code by setting isDelete to true and status to INACTIVE
    await QRCodeModel.findByIdAndUpdate(
      id as any,
      {
        isDelete: true,
        status: 'INACTIVE',
      },
      { new: true }
    );

    return res.json(
      UniResponse.Success('QR code deleted successfully', null, StatusCode.OK)
    );
  });

  // ========== ADMIN STATICTICS ===========
  public static getAllAdminAnalytics = asyncHandler(
    async (req: Request, res: Response) => {
      const startTime = Date.now();
      const requestId = Math.random().toString(36).substring(7);

      console.log(`🔍 [${requestId}] ADMIN_ANALYTICS_STARTED`, {
        timestamp: new Date().toISOString(),
        method: req.method,
        url: req.url,
        queryParams: req.query,
      });

      // Validate query parameters
      const validationResult = AdminValidation.validateGetAdminAnalyticsQuery(
        req.query
      );
      if (!ValidationUtils.isValidationSuccess(validationResult)) {
        return res.json(
          UniResponse.Error(
            ValidationUtils.formatValidationError(validationResult.error),
            StatusCode.BAD_REQUEST
          )
        );
      }

      const { period } = ValidationUtils.getValidatedData(validationResult);

      // Calculate date range based on period
      const { startDate, endDate, periodLabel, intervalDays } =
        AdminController.calculateDateRange(period);

      // Use single aggregation pipeline to get all analytics data efficiently
      const [analyticsData, recentActivity, topPerformingQrcodes] = await Promise.all([
        AdminController.getOptimizedAnalyticsData(
          startDate,
          endDate,
          requestId,
          period,
          intervalDays
        ),
        AdminController.generateRecentActivityAnalytics(requestId),
        AdminController.getTopPerformingQrcodes(),
      ]);

      console.timeEnd(`⏱️ [${requestId}] OPTIMIZED_ANALYTICS_DURATION`);

      const response = {
        period: periodLabel,
        dateRange: {
          startDate: startDate.toISOString(),
          endDate: endDate.toISOString(),
        },
        kpis: analyticsData.kpis,
        summary: analyticsData.summary,
        scanData: analyticsData.scanData,
        qrTypeData: analyticsData.qrTypeData,
        recentActivity,
        topPerformingQrcodes,
        dailyAnalytics: analyticsData.dailyAnalytics,
      };

      const duration = Date.now() - startTime;

      return res.json(
        UniResponse.Success(StatusCode.getReasonPhrase(StatusCode.OK), response, 200)
      );
    }
  );

  // ========== ADMIN ANALYTICS PDF DOCUMENT ===========
  public static getAdminAnalyticsDocument = asyncHandler(
    async (req: Request, res: Response) => {
      const startTime = Date.now();
      const requestId = Math.random().toString(36).substring(7);

      console.log(`🔍 [${requestId}] ADMIN_ANALYTICS_PDF_STARTED`, {
        timestamp: new Date().toISOString(),
        method: req.method,
        url: req.url,
        queryParams: req.query,
      });

      // Validate query parameters
      const validationResult = AdminValidation.validateGetAdminAnalyticsQuery(
        req.query
      );
      if (!ValidationUtils.isValidationSuccess(validationResult)) {
        return res.json(
          UniResponse.Error(
            ValidationUtils.formatValidationError(validationResult.error),
            StatusCode.BAD_REQUEST
          )
        );
      }

      const { period } = ValidationUtils.getValidatedData(validationResult);

      // Calculate date range based on period
      const { startDate, endDate, periodLabel, intervalDays } =
        AdminController.calculateDateRange(period);

      // Get analytics data
      const [analyticsData, recentActivity, topPerformingQrcodes] = await Promise.all([
        AdminController.getOptimizedAnalyticsData(
          startDate,
          endDate,
          requestId,
          period,
          intervalDays
        ),
        AdminController.generateRecentActivityAnalytics(requestId),
        AdminController.getTopPerformingQrcodes(),
      ]);

      // Create PDF document
      const doc = new jsPDF();
      const pageWidth = doc.internal.pageSize.getWidth();
      const pageHeight = doc.internal.pageSize.getHeight();
      const margin = 20;
      let yPosition = margin;

      // Load favicon/logo
      const isProduction = process.env.NODE_ENV === 'production';
      const faviconPath = isProduction
        ? resolve(__dirname, '../uploads/quick-connect.ico')
        : resolve(__dirname, '../../uploads/quick-connect.ico');

      let logoData = '';
      if (existsSync(faviconPath)) {
        try {
          const logoBuffer = readFileSync(faviconPath);
          logoData = 'data:image/x-icon;base64,' + logoBuffer.toString('base64');
        } catch (error) {
          console.warn('Could not load logo:', error);
        }
      }

      // Header with logo and title
      if (logoData) {
        try {
          doc.addImage(logoData, 'ICO', margin, yPosition, 20, 20);
        } catch (error) {
          console.warn('Could not add logo image:', error);
        }
      }

      doc.setFontSize(24);
      doc.setFont('helvetica', 'bold');
      doc.text(
        'Admin Analytics Report',
        logoData ? margin + 25 : margin,
        yPosition + 12
      );

      doc.setFontSize(10);
      doc.setFont('helvetica', 'normal');
      doc.setTextColor(100, 100, 100);
      doc.text(`Period: ${periodLabel}`, pageWidth - margin, yPosition + 8, {
        align: 'right',
      });
      doc.text(
        `Generated: ${new Date().toLocaleString()}`,
        pageWidth - margin,
        yPosition + 14,
        { align: 'right' }
      );
      doc.setTextColor(0, 0, 0);

      yPosition += 35;

      // Date Range
      doc.setFontSize(11);
      doc.setFont('helvetica', 'bold');
      doc.text('Date Range:', margin, yPosition);
      doc.setFont('helvetica', 'normal');
      doc.text(
        `${startDate.toLocaleDateString()} - ${endDate.toLocaleDateString()}`,
        margin + 40,
        yPosition
      );
      yPosition += 15;

      // KPIs Section
      doc.setFontSize(14);
      doc.setFont('helvetica', 'bold');
      doc.setTextColor(30, 58, 138); // Blue color
      doc.text('Key Performance Indicators', margin, yPosition);
      doc.setTextColor(0, 0, 0);
      yPosition += 10;

      const kpiData = [
        ['Metric', 'Value'],
        ['Active Users', analyticsData.kpis.activeUsers.toString()],
        ['Total Users', analyticsData.kpis.totalUsers.toString()],
        ['Total QR Codes', analyticsData.kpis.totalQrCodes.toString()],
        ['Average Daily Scans', analyticsData.kpis.avgDailyScans.toString()],
        ['Pending Reports', (analyticsData.kpis.reports || 0).toString()],
      ];

      autoTable(doc, {
        startY: yPosition,
        head: [kpiData[0]],
        body: kpiData.slice(1),
        theme: 'striped',
        headStyles: { fillColor: [30, 58, 138], textColor: 255, fontStyle: 'bold' },
        margin: { left: margin, right: margin },
      });

      yPosition = (doc as any).lastAutoTable?.finalY
        ? (doc as any).lastAutoTable.finalY + 15
        : yPosition + 60;

      // Summary Section
      doc.setFontSize(14);
      doc.setFont('helvetica', 'bold');
      doc.setTextColor(30, 58, 138);
      doc.text('Summary Statistics', margin, yPosition);
      doc.setTextColor(0, 0, 0);
      yPosition += 10;

      const summaryData = [
        ['Metric', 'Value'],
        ['Total Scans', analyticsData.summary.totalScans.toString()],
        ['Successful Scans', analyticsData.summary.totalSuccessfulScans.toString()],
        ['Failed Scans', analyticsData.summary.totalFailedScans.toString()],
        ['Success Rate', `${analyticsData.summary.successRate}%`],
        ['Average Daily Scans', analyticsData.summary.avgDailyScans.toString()],
      ];

      autoTable(doc, {
        startY: yPosition,
        head: [summaryData[0]],
        body: summaryData.slice(1),
        theme: 'striped',
        headStyles: { fillColor: [30, 58, 138], textColor: 255, fontStyle: 'bold' },
        margin: { left: margin, right: margin },
      });

      yPosition = (doc as any).lastAutoTable?.finalY
        ? (doc as any).lastAutoTable.finalY + 15
        : yPosition + 60;

      // Daily Analytics Table
      if (analyticsData.dailyAnalytics && analyticsData.dailyAnalytics.length > 0) {
        // Check if we need a new page
        if (yPosition > pageHeight - 80) {
          doc.addPage();
          yPosition = margin;
        }

        doc.setFontSize(14);
        doc.setFont('helvetica', 'bold');
        doc.setTextColor(30, 58, 138);
        doc.text('Daily Analytics', margin, yPosition);
        doc.setTextColor(0, 0, 0);
        yPosition += 10;

        const dailyData = [
          [
            'Date',
            'Total Scans',
            'Successful',
            'Failed',
            'Blocked',
            'Expired',
            'Success Rate %',
          ],
        ];

        analyticsData.dailyAnalytics.forEach((day: any) => {
          dailyData.push([
            day.displayDate || day.date || day.dayName || '',
            day.totalScans?.toString() || '0',
            day.successfulScans?.toString() || '0',
            day.failedScans?.toString() || '0',
            day.blockedScans?.toString() || '0',
            day.expiredScans?.toString() || '0',
            day.successRate || '0.00',
          ]);
        });

        autoTable(doc, {
          startY: yPosition,
          head: [dailyData[0]],
          body: dailyData.slice(1),
          theme: 'striped',
          headStyles: { fillColor: [30, 58, 138], textColor: 255, fontStyle: 'bold' },
          margin: { left: margin, right: margin },
          styles: { fontSize: 8 },
        });

        yPosition = (doc as any).lastAutoTable?.finalY
          ? (doc as any).lastAutoTable.finalY + 15
          : yPosition + 100;
      }

      // QR Type Distribution
      if (analyticsData.qrTypeData && analyticsData.qrTypeData.length > 0) {
        if (yPosition > pageHeight - 80) {
          doc.addPage();
          yPosition = margin;
        }

        doc.setFontSize(14);
        doc.setFont('helvetica', 'bold');
        doc.setTextColor(30, 58, 138);
        doc.text('QR Code Type Distribution', margin, yPosition);
        doc.setTextColor(0, 0, 0);
        yPosition += 10;

        const qrTypeTable = [['QR Type', 'Count', 'Percentage']];

        analyticsData.qrTypeData.forEach((type: any) => {
          qrTypeTable.push([
            type.name || '',
            type.count?.toString() || '0',
            `${type.value || 0}%`,
          ]);
        });

        autoTable(doc, {
          startY: yPosition,
          head: [qrTypeTable[0]],
          body: qrTypeTable.slice(1),
          theme: 'striped',
          headStyles: { fillColor: [30, 58, 138], textColor: 255, fontStyle: 'bold' },
          margin: { left: margin, right: margin },
        });

        yPosition = (doc as any).lastAutoTable?.finalY
          ? (doc as any).lastAutoTable.finalY + 15
          : yPosition + 60;
      }

      // Recent Activity
      if (recentActivity) {
        if (yPosition > pageHeight - 100) {
          doc.addPage();
          yPosition = margin;
        }

        doc.setFontSize(14);
        doc.setFont('helvetica', 'bold');
        doc.setTextColor(30, 58, 138);
        doc.text('Recent Activity (Today)', margin, yPosition);
        doc.setTextColor(0, 0, 0);
        yPosition += 10;

        const recentActivityData = [
          ['Metric', 'Value'],
          ['QR Codes Created Today', (recentActivity.QrcodeToday || 0).toString()],
          [
            'New Registered Users Today',
            (recentActivity.NewRegisteredUsersToday || 0).toString(),
          ],
          ['Daily Active Users', (recentActivity.DailyActiveUsers || 0).toString()],
        ];

        autoTable(doc, {
          startY: yPosition,
          head: [recentActivityData[0]],
          body: recentActivityData.slice(1),
          theme: 'striped',
          headStyles: { fillColor: [30, 58, 138], textColor: 255, fontStyle: 'bold' },
          margin: { left: margin, right: margin },
        });

        yPosition = (doc as any).lastAutoTable?.finalY
          ? (doc as any).lastAutoTable.finalY + 15
          : yPosition + 60;
      }

      // Top Performing QR Codes
      if (topPerformingQrcodes && topPerformingQrcodes.length > 0) {
        if (yPosition > pageHeight - 100) {
          doc.addPage();
          yPosition = margin;
        }

        doc.setFontSize(14);
        doc.setFont('helvetica', 'bold');
        doc.setTextColor(30, 58, 138);
        doc.text('Top Performing QR Codes', margin, yPosition);
        doc.setTextColor(0, 0, 0);
        yPosition += 10;

        const topQrCodesData = [['QR Code Title', 'Type', 'Total Scans']];

        topPerformingQrcodes.slice(0, 10).forEach((qr: any) => {
          topQrCodesData.push([
            qr.qrcode?.title || 'N/A',
            qr.qrcode?.type || 'N/A',
            qr.totalScans?.toString() || '0',
          ]);
        });

        autoTable(doc, {
          startY: yPosition,
          head: [topQrCodesData[0]],
          body: topQrCodesData.slice(1),
          theme: 'striped',
          headStyles: { fillColor: [30, 58, 138], textColor: 255, fontStyle: 'bold' },
          margin: { left: margin, right: margin },
        });
      }

      // Footer on last page
      const pageCount = doc.getNumberOfPages();
      for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.setFontSize(8);
        doc.setTextColor(100, 100, 100);
        doc.text(`Page ${i} of ${pageCount}`, pageWidth / 2, pageHeight - 10, {
          align: 'center',
        });
        doc.text(
          'Quick Connect - Admin Analytics Report',
          pageWidth / 2,
          pageHeight - 5,
          { align: 'center' }
        );
      }

      // Generate PDF buffer
      const pdfBuffer = Buffer.from(doc.output('arraybuffer'));

      // Create reports directory if it doesn't exist
      // Use root-level uploads directory for both production and development
      const baseUploadsDir = path.join(process.cwd(), 'uploads');
      const reportsDir = path.join(baseUploadsDir, 'reports');
      if (!fs.existsSync(reportsDir)) {
        fs.mkdirSync(reportsDir, { recursive: true });
      }

      // Generate unique filename
      const timestamp = new Date().toISOString().split('T')[0];
      const uniqueId = Date.now() + '-' + Math.round(Math.random() * 1e9);
      const filename = `admin-analytics-${period}-${timestamp}-${uniqueId}.pdf`;
      const filePath = path.join(reportsDir, filename);

      // Save PDF buffer to file
      fs.writeFileSync(filePath, pdfBuffer);

      // Construct download URL
      // Use req.get('host') to include port number when needed
      const baseUrl = process.env.BASE_URL || `${req.protocol}://${req.get('host')}`;
      const downloadUrl = `${baseUrl}/uploads/reports/${filename}`;

      const duration = Date.now() - startTime;
      console.log(`✅ [${requestId}] ADMIN_ANALYTICS_PDF_COMPLETED in ${duration}ms`);

      // Return JSON response with download link
      return res.json(
        UniResponse.Success(
          'Admin analytics PDF document generated successfully',
          {
            downloadUrl,
            filename,
            period: period,
            generatedAt: new Date().toISOString(),
          },
          200
        )
      );
    }
  );

  // Calculate date range based on period
  private static calculateDateRange(period: string) {
    const now = new Date();
    const endDate = new Date(now);
    endDate.setHours(23, 59, 59, 999);

    let startDate: Date;
    let periodLabel: string;
    let intervalDays: number;

    switch (period) {
      case '30days':
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 29); // 29 days ago + today = 30 days
        startDate.setHours(0, 0, 0, 0);
        periodLabel = '30 days';
        intervalDays = 30;
        break;

      case '90days':
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 89); // 89 days ago + today = 90 days
        startDate.setHours(0, 0, 0, 0);
        periodLabel = '90 days';
        intervalDays = 90;
        break;

      case 'year':
        startDate = new Date(now);
        startDate.setFullYear(now.getFullYear() - 1);
        startDate.setHours(0, 0, 0, 0);
        periodLabel = 'Last Year';
        intervalDays = 365;
        break;

      case '7days':
      default:
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 6); // 6 days ago + today = 7 days
        startDate.setHours(0, 0, 0, 0);
        periodLabel = '7 days';
        intervalDays = 7;
        break;
    }

    return { startDate, endDate, periodLabel, intervalDays };
  }

  // Helper function to get scan analytics by date and status
  private static async getScanAnalytics(
    startDate: Date,
    endDate: Date
  ): Promise<any[]> {
    const scans = await ScanModel.find({
      createdAt: { $gte: startDate, $lte: endDate },
    })
      .select('createdAt scan_status')
      .lean();

    // Group scans by date and status
    const scanMap = new Map<string, Map<string, number>>();

    scans.forEach((scan: any) => {
      const dateStr = new Date(scan.createdAt).toISOString().split('T')[0];
      const status = scan.scan_status || 'SUCCESS';

      if (!scanMap.has(dateStr)) {
        scanMap.set(dateStr, new Map<string, number>());
      }

      const statusMap = scanMap.get(dateStr)!;
      statusMap.set(status, (statusMap.get(status) || 0) + 1);
    });

    // Convert to array format matching the original aggregation result
    const result: any[] = [];
    scanMap.forEach((statusMap, date) => {
      const scans: any[] = [];
      let totalScans = 0;

      statusMap.forEach((count, status) => {
        scans.push({ status, count });
        totalScans += count;
      });

      result.push({
        _id: date,
        scans,
        totalScans,
      });
    });

    // Sort by date
    result.sort((a, b) => a._id.localeCompare(b._id));

    return result;
  }

  // Helper function to get total active users count
  private static async getTotalActiveUsers(): Promise<number> {
    return await UserModel.countDocuments({
      is_delete: false,
      status: 'ACTIVE',
    });
  }

  // Helper function to get active users in date range
  private static async getActiveUsersInRange(startDate: Date): Promise<number> {
    return await UserModel.countDocuments({
      is_delete: false,
      status: 'ACTIVE',
      updatedAt: { $gte: startDate },
    });
  }

  // Helper function to get daily user activity
  private static async getDailyUserActivity(
    startDate: Date,
    endDate: Date
  ): Promise<any[]> {
    const users = await UserModel.find({
      is_delete: false,
      status: 'ACTIVE',
      updatedAt: { $gte: startDate, $lte: endDate },
    })
      .select('updatedAt')
      .lean();

    // Group users by date
    const activityMap = new Map<string, number>();

    users.forEach(user => {
      const dateStr = new Date(user.updatedAt).toISOString().split('T')[0];
      activityMap.set(dateStr, (activityMap.get(dateStr) || 0) + 1);
    });

    // Convert to array format
    const result: any[] = [];
    activityMap.forEach((users, date) => {
      result.push({
        _id: date,
        users,
      });
    });

    // Sort by date
    result.sort((a, b) => a._id.localeCompare(b._id));

    return result;
  }

  // Helper function to get total QR codes count
  private static async getTotalQrCodes(): Promise<number> {
    return await QRCodeModel.countDocuments({
      status: 'ACTIVE',
      isDelete: false,
    });
  }

  // Helper function to get QR type distribution
  private static async getQrTypeDistribution(
    startDate: Date,
    endDate: Date
  ): Promise<any[]> {
    const qrCodes = await QRCodeModel.find({
      status: 'ACTIVE',
      isDelete: false,
      created_at: { $gte: startDate, $lte: endDate },
    })
      .select('type')
      .lean();

    // Group by type
    const typeMap = new Map<string, number>();

    qrCodes.forEach(qrCode => {
      const type = qrCode.type || 'UNKNOWN';
      typeMap.set(type, (typeMap.get(type) || 0) + 1);
    });

    // Convert to array format
    const result: any[] = [];
    typeMap.forEach((count, type) => {
      result.push({
        _id: type,
        count,
      });
    });

    return result;
  }

  // Helper function to get daily QR code creation
  private static async getDailyQrCreation(
    startDate: Date,
    endDate: Date
  ): Promise<any[]> {
    const qrCodes = await QRCodeModel.find({
      status: 'ACTIVE',
      isDelete: false,
      created_at: { $gte: startDate, $lte: endDate },
    })
      .select('created_at')
      .lean();

    // Group by date
    const creationMap = new Map<string, number>();

    qrCodes.forEach(qrCode => {
      const dateStr = new Date(qrCode.created_at).toISOString().split('T')[0];
      creationMap.set(dateStr, (creationMap.get(dateStr) || 0) + 1);
    });

    // Convert to array format
    const result: any[] = [];
    creationMap.forEach((qrCodes, date) => {
      result.push({
        _id: date,
        qrCodes,
      });
    });

    // Sort by date
    result.sort((a, b) => a._id.localeCompare(b._id));

    return result;
  }

  // Helper function to get pending contact reports
  private static async getPendingReports(): Promise<number> {
    return await ContactModel.countDocuments({
      contact_status: 'pending',
    });
  }

  // Optimized method to get all analytics data with minimal database queries
  private static async getOptimizedAnalyticsData(
    startDate: Date,
    endDate: Date,
    requestId: string,
    period: string = '7days',
    intervalDays: number = 7
  ) {
    console.log(`🚀 [${requestId}] STARTING_OPTIMIZED_ANALYTICS`);

    // Execute all queries in parallel
    const [
      scanAnalytics,
      totalActiveUsers,
      activeUsersLast7Days,
      dailyUserActivity,
      totalQrCodes,
      qrTypeDistribution,
      dailyQrCreation,
      totalReports,
    ] = await Promise.all([
      this.getScanAnalytics(startDate, endDate),
      this.getTotalActiveUsers(),
      this.getActiveUsersInRange(startDate),
      this.getDailyUserActivity(startDate, endDate),
      this.getTotalQrCodes(),
      this.getQrTypeDistribution(startDate, endDate),
      this.getDailyQrCreation(startDate, endDate),
      this.getPendingReports(),
    ]);

    console.log(`📊 [${requestId}] RAW_DATA_RETRIEVED`);

    // Process scan analytics data
    const dailyAnalytics = AdminController.processDailyAnalytics(
      scanAnalytics,
      startDate,
      endDate,
      period
    );
    const scanData = AdminController.processScanData(
      scanAnalytics,
      dailyUserActivity,
      dailyQrCreation,
      startDate,
      endDate,
      period
    );

    // Process QR type data
    const qrTypeData = AdminController.processQrTypeData(qrTypeDistribution);

    // Calculate summary statistics
    const totalScans = dailyAnalytics.reduce(
      (sum: number, day: any) => sum + day.totalScans,
      0
    );
    const totalSuccessfulScans = dailyAnalytics.reduce(
      (sum: number, day: any) => sum + day.successfulScans,
      0
    );
    const totalFailedScans = dailyAnalytics.reduce(
      (sum: number, day: any) => sum + day.failedScans,
      0
    );
    const avgDailyScans =
      totalScans > 0 ? parseFloat((totalScans / intervalDays).toFixed(1)) : 0;

    const kpis = {
      activeUsers: activeUsersLast7Days,
      totalUsers: totalActiveUsers,
      totalQrCodes: totalQrCodes,
      avgDailyScans,
      reports: totalReports,
    };

    const summary = {
      totalScans,
      totalSuccessfulScans,
      totalFailedScans,
      successRate:
        totalScans > 0
          ? ((totalSuccessfulScans / totalScans) * 100).toFixed(2)
          : '0.00',
      avgDailyScans,
    };

    return {
      kpis,
      summary,
      scanData,
      qrTypeData,
      dailyAnalytics,
    };
  }

  // Process daily analytics from aggregated scan data
  private static processDailyAnalytics(
    scanAnalytics: any[],
    startDate: Date,
    endDate: Date,
    period: string = '7days'
  ) {
    const dailyMap = new Map();

    // Calculate number of days based on period
    const daysDiff =
      Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)) + 1;

    // For longer periods, we might want to group data differently
    if (period === 'year') {
      // For yearly data, group by months
      return AdminController.processMonthlyAnalytics(scanAnalytics, startDate, endDate);
    } else if (period === '90days') {
      // For 90 days, group by weeks
      return AdminController.processWeeklyAnalytics(scanAnalytics, startDate, endDate);
    }

    // For 7days and 30days, show daily data
    // Initialize all days with zero values
    const daysToShow = period === '7days' ? 7 : Math.min(daysDiff, 30);
    for (let i = 0; i < daysToShow; i++) {
      const date = new Date(startDate);
      date.setDate(startDate.getDate() + i);
      const dateStr = date.toISOString().split('T')[0];
      const dayName = date.toLocaleDateString('en-US', { weekday: 'short' });
      const displayDate = date.toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
      });

      dailyMap.set(dateStr, {
        date: dateStr,
        dayName,
        displayDate,
        totalScans: 0,
        successfulScans: 0,
        failedScans: 0,
        blockedScans: 0,
        expiredScans: 0,
        successRate: '0.00',
      });
    }

    // Fill in actual data
    scanAnalytics.forEach(dayData => {
      const dayStats = dailyMap.get(dayData._id);
      if (dayStats) {
        dayStats.totalScans = dayData.totalScans;

        dayData.scans.forEach((scan: any) => {
          switch (scan.status) {
            case 'SUCCESS':
              dayStats.successfulScans = scan.count;
              break;
            case 'FAILED':
              dayStats.failedScans = scan.count;
              break;
            case 'BLOCKED':
              dayStats.blockedScans = scan.count;
              break;
            case 'EXPIRED':
              dayStats.expiredScans = scan.count;
              break;
          }
        });

        dayStats.successRate =
          dayStats.totalScans > 0
            ? ((dayStats.successfulScans / dayStats.totalScans) * 100).toFixed(2)
            : '0.00';
      }
    });

    return Array.from(dailyMap.values());
  }

  // Process monthly analytics for yearly data
  private static processMonthlyAnalytics(
    scanAnalytics: any[],
    startDate: Date,
    endDate: Date
  ) {
    const monthlyMap = new Map();
    const monthNames = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ];

    // Initialize 12 months
    for (let i = 0; i < 12; i++) {
      const date = new Date(startDate);
      date.setMonth(startDate.getMonth() + i);
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      const monthName = monthNames[date.getMonth()];

      monthlyMap.set(monthKey, {
        date: monthKey,
        dayName: monthName,
        displayDate: monthName,
        totalScans: 0,
        successfulScans: 0,
        failedScans: 0,
        blockedScans: 0,
        expiredScans: 0,
        successRate: '0.00',
      });
    }

    // Aggregate daily data into monthly
    scanAnalytics.forEach(dayData => {
      const date = new Date(dayData._id);
      const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      const monthStats = monthlyMap.get(monthKey);

      if (monthStats) {
        monthStats.totalScans += dayData.totalScans;

        dayData.scans.forEach((scan: any) => {
          switch (scan.status) {
            case 'SUCCESS':
              monthStats.successfulScans += scan.count;
              break;
            case 'FAILED':
              monthStats.failedScans += scan.count;
              break;
            case 'BLOCKED':
              monthStats.blockedScans += scan.count;
              break;
            case 'EXPIRED':
              monthStats.expiredScans += scan.count;
              break;
          }
        });
      }
    });

    // Calculate success rates
    Array.from(monthlyMap.values()).forEach(month => {
      month.successRate =
        month.totalScans > 0
          ? ((month.successfulScans / month.totalScans) * 100).toFixed(2)
          : '0.00';
    });

    return Array.from(monthlyMap.values());
  }

  // Process weekly analytics for 90-day data
  private static processWeeklyAnalytics(
    scanAnalytics: any[],
    startDate: Date,
    endDate: Date
  ) {
    const weeklyMap = new Map();

    // Initialize weeks (approximately 13 weeks for 90 days)
    const weekCount = Math.ceil(
      (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24 * 7)
    );
    for (let i = 0; i < weekCount; i++) {
      const weekStart = new Date(startDate);
      weekStart.setDate(startDate.getDate() + i * 7);
      const weekKey = `Week ${i + 1}`;
      const displayDate = weekStart.toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
      });

      weeklyMap.set(i, {
        date: weekStart.toISOString().split('T')[0],
        dayName: weekKey,
        displayDate: `${weekKey} (${displayDate})`,
        totalScans: 0,
        successfulScans: 0,
        failedScans: 0,
        blockedScans: 0,
        expiredScans: 0,
        successRate: '0.00',
        weekStart: weekStart,
        weekEnd: new Date(weekStart.getTime() + 6 * 24 * 60 * 60 * 1000),
      });
    }

    // Aggregate daily data into weekly
    scanAnalytics.forEach(dayData => {
      const date = new Date(dayData._id);

      // Find which week this day belongs to
      for (const [weekIndex, weekStats] of weeklyMap.entries()) {
        if (date >= weekStats.weekStart && date <= weekStats.weekEnd) {
          weekStats.totalScans += dayData.totalScans;

          dayData.scans.forEach((scan: any) => {
            switch (scan.status) {
              case 'SUCCESS':
                weekStats.successfulScans += scan.count;
                break;
              case 'FAILED':
                weekStats.failedScans += scan.count;
                break;
              case 'BLOCKED':
                weekStats.blockedScans += scan.count;
                break;
              case 'EXPIRED':
                weekStats.expiredScans += scan.count;
                break;
            }
          });
          break;
        }
      }
    });

    // Calculate success rates and clean up
    const result = Array.from(weeklyMap.values()).map(week => {
      const { weekStart, weekEnd, ...cleanWeek } = week;
      cleanWeek.successRate =
        cleanWeek.totalScans > 0
          ? ((cleanWeek.successfulScans / cleanWeek.totalScans) * 100).toFixed(2)
          : '0.00';
      return cleanWeek;
    });

    return result;
  }

  // Process scan data for charts
  private static processScanData(
    scanAnalytics: any[],
    userActivity: any[],
    qrActivity: any[],
    startDate: Date,
    endDate: Date,
    period: string = '7days'
  ) {
    const scanDataMap = new Map();
    const userActivityMap = new Map();
    const qrActivityMap = new Map();

    // Create maps for quick lookup
    scanAnalytics.forEach(day => {
      const successfulScans =
        day.scans.find((s: any) => s.status === 'SUCCESS')?.count || 0;
      scanDataMap.set(day._id, successfulScans);
    });

    userActivity.forEach(day => {
      userActivityMap.set(day._id, day.users);
    });

    qrActivity.forEach(day => {
      qrActivityMap.set(day._id, day.qrCodes);
    });

    // Handle different periods
    if (period === 'year') {
      return AdminController.processMonthlyChartData(
        scanDataMap,
        userActivityMap,
        qrActivityMap,
        startDate,
        endDate
      );
    } else if (period === '90days') {
      return AdminController.processWeeklyChartData(
        scanDataMap,
        userActivityMap,
        qrActivityMap,
        startDate,
        endDate
      );
    }

    // For 7days and 30days, show daily data
    const dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    const scanData = [];
    const daysToShow = period === '7days' ? 7 : 30;

    for (let i = 0; i < daysToShow; i++) {
      const date = new Date(startDate);
      date.setDate(startDate.getDate() + i);
      const dateStr = date.toISOString().split('T')[0];

      let dayName: string;
      if (period === '7days') {
        dayName = dayNames[date.getDay()];
      } else {
        // For 30 days, show date instead of day name
        dayName = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
      }

      scanData.push({
        name: dayName,
        scans: scanDataMap.get(dateStr) || 0,
        users: userActivityMap.get(dateStr) || 0,
        qrCodes: qrActivityMap.get(dateStr) || 0,
      });
    }

    return scanData;
  }

  // Process monthly chart data for yearly view
  private static processMonthlyChartData(
    scanDataMap: Map<string, number>,
    userActivityMap: Map<string, number>,
    qrActivityMap: Map<string, number>,
    startDate: Date,
    endDate: Date
  ) {
    const monthNames = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec',
    ];
    const monthlyData = [];

    for (let i = 0; i < 12; i++) {
      const date = new Date(startDate);
      date.setMonth(startDate.getMonth() + i);
      const monthName = monthNames[date.getMonth()];

      // Aggregate data for the entire month
      let monthScans = 0;
      let monthUsers = 0;
      let monthQrCodes = 0;

      // Get all days in this month
      const daysInMonth = new Date(
        date.getFullYear(),
        date.getMonth() + 1,
        0
      ).getDate();
      for (let day = 1; day <= daysInMonth; day++) {
        const dayDate = new Date(date.getFullYear(), date.getMonth(), day);
        const dayStr = dayDate.toISOString().split('T')[0];

        monthScans += scanDataMap.get(dayStr) || 0;
        monthUsers += userActivityMap.get(dayStr) || 0;
        monthQrCodes += qrActivityMap.get(dayStr) || 0;
      }

      monthlyData.push({
        name: monthName,
        scans: monthScans,
        users: monthUsers,
        qrCodes: monthQrCodes,
      });
    }

    return monthlyData;
  }

  // Process weekly chart data for 90-day view
  private static processWeeklyChartData(
    scanDataMap: Map<string, number>,
    userActivityMap: Map<string, number>,
    qrActivityMap: Map<string, number>,
    startDate: Date,
    endDate: Date
  ) {
    const weeklyData = [];
    const weekCount = Math.ceil(
      (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24 * 7)
    );

    for (let i = 0; i < weekCount; i++) {
      const weekStart = new Date(startDate);
      weekStart.setDate(startDate.getDate() + i * 7);
      const weekEnd = new Date(weekStart.getTime() + 6 * 24 * 60 * 60 * 1000);

      const weekName = `Week ${i + 1}`;

      // Aggregate data for the entire week
      let weekScans = 0;
      let weekUsers = 0;
      let weekQrCodes = 0;

      for (let day = 0; day < 7; day++) {
        const dayDate = new Date(weekStart);
        dayDate.setDate(weekStart.getDate() + day);
        const dayStr = dayDate.toISOString().split('T')[0];

        weekScans += scanDataMap.get(dayStr) || 0;
        weekUsers += userActivityMap.get(dayStr) || 0;
        weekQrCodes += qrActivityMap.get(dayStr) || 0;
      }

      weeklyData.push({
        name: weekName,
        scans: weekScans,
        users: weekUsers,
        qrCodes: weekQrCodes,
      });
    }

    return weeklyData;
  }

  // Process QR type data
  private static processQrTypeData(qrTypeStats: any[]) {
    const typeMapping = {
      CAR: { name: 'Car QR', color: '#3B82F6' },
      PET: { name: 'Pet Tag', color: '#10B981' },
      LUGGAGE: { name: 'Luggage', color: '#F59E0B' },
      MEDICAL_QR: { name: 'Medical', color: '#EF4444' },
      MEMORY_TAG: { name: 'Memory Tag', color: '#8B5CF6' },
      IDENTIFICATIONS: { name: 'ID Tag', color: '#6366F1' },
      DOCUMENT: { name: 'Document', color: '#EC4899' },
    };

    const totalQrCodes = qrTypeStats.reduce((sum, type) => sum + type.count, 0);

    const qrTypeData = qrTypeStats.map(stat => {
      const typeInfo = typeMapping[stat._id as keyof typeof typeMapping] || {
        name: stat._id,
        color: '#6B7280',
      };
      const percentage =
        totalQrCodes > 0 ? Math.round((stat.count / totalQrCodes) * 100) : 0;

      return {
        name: typeInfo.name,
        value: percentage,
        color: typeInfo.color,
        count: stat.count,
      };
    });

    // Sort by percentage (descending)
    qrTypeData.sort((a, b) => b.value - a.value);

    return qrTypeData;
  }

  // Generate recent activity analytics for today's statistics
  private static async generateRecentActivityAnalytics(requestId: string) {
    // Calculate today's date range (start of today to end of today)
    const now = new Date();
    const startOfToday = new Date(now);
    startOfToday.setHours(0, 0, 0, 0);

    const endOfToday = new Date(now);
    endOfToday.setHours(23, 59, 59, 999);

    // ================== QRCODE TODAY ==================
    const qrCodeToday = await QRCodeModel.countDocuments({
      $or: [
        { created_at: { $gte: startOfToday, $lte: endOfToday } },
        { createdAt: { $gte: startOfToday, $lte: endOfToday } },
      ],
    });

    // =========== NEW REGISTERED USERS TODAY ==================
    const newRegisteredUsersToday = await UserModel.countDocuments({
      $or: [
        { created_at: { $gte: startOfToday, $lte: endOfToday } },
        { createdAt: { $gte: startOfToday, $lte: endOfToday } },
      ],
      is_delete: false,
    });

    // =========== DAILY ACTIVE USERS (users active today) ==================
    const dailyActiveUsers = await UserModel.countDocuments({
      isLogin: true,
      $or: [
        { updatedAt: { $gte: startOfToday, $lte: endOfToday } },
        { updated_at: { $gte: startOfToday, $lte: endOfToday } },
      ],
    });

    // ================== TOP QRCODES ===============
    const topQrcodes = await this.getTopQrcodes();

    return {
      QrcodeToday: qrCodeToday,
      NewRegisteredUsersToday: newRegisteredUsersToday,
      DailyActiveUsers: dailyActiveUsers,
      TopQrcodes: topQrcodes,
    };
  }

  // =========== GET ANALYTICS DATE RANGE ==============
  private static getAnalyticsDateRange(period: string) {
    const now = new Date();
    let startDate: Date;
    let endDate: Date = new Date(now); // Initialize endDate to current date
    let labels: string[] = [];
    let dateKeys: string[] = []; // Keep track of actual date keys for mapping

    switch (period) {
      case '1d':
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 1);
        startDate.setHours(0, 0, 0, 0);

        // For 1 day, we'll show hourly breakdown
        labels = Array.from({ length: 24 }, (_, i) => `${i}:00`);
        // For hourly, we'll need to format the dates differently
        dateKeys = Array.from({ length: 24 }, (_, i) => {
          const date = new Date(now);
          date.setHours(i, 0, 0, 0);
          return this.toISODate(date) || '';
        });
        break;

      case '7d':
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 6); // 6 days ago + today = 7 days
        startDate.setHours(0, 0, 0, 0);

        // Generate labels for the last 7 days and their corresponding date keys
        for (let i = 6; i >= 0; i--) {
          const date = new Date(now);
          date.setDate(now.getDate() - i);
          labels.push(date.toLocaleDateString('en-US', { weekday: 'short' }));
          dateKeys.push(this.toISODate(date) || '');
        }
        break;

      case '30d':
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 29); // 29 days ago + today = 30 days
        startDate.setHours(0, 0, 0, 0);

        // For 30 days, generate date keys for each day
        for (let i = 29; i >= 0; i--) {
          const date = new Date(now);
          date.setDate(now.getDate() - i);
          dateKeys.push(this.toISODate(date) || '');
        }

        // For labels, we'll show every 5 days or so to avoid clutter
        labels = [];
        for (let i = 0; i < 30; i += 5) {
          const date = new Date(now);
          date.setDate(now.getDate() - (29 - i));
          labels.push(
            date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
          );
        }
        break;

      case '1y':
        startDate = new Date(now);
        startDate.setFullYear(now.getFullYear() - 1);
        startDate.setHours(0, 0, 0, 0);

        // For 1 year, generate date keys for each month
        dateKeys = [];
        for (let i = 0; i < 12; i++) {
          const date = new Date(now);
          date.setMonth(now.getMonth() - (11 - i));
          dateKeys.push(this.toISODate(date) || '');
        }

        // For 1 year, we'll show monthly labels
        labels = [];
        const monthNames = [
          'Jan',
          'Feb',
          'Mar',
          'Apr',
          'May',
          'Jun',
          'Jul',
          'Aug',
          'Sep',
          'Oct',
          'Nov',
          'Dec',
        ];
        const startMonth = startDate.getMonth();
        for (let i = 0; i < 12; i++) {
          labels.push(monthNames[(startMonth + i) % 12]);
        }
        break;

      default:
        // Default to 7 days
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 6);
        startDate.setHours(0, 0, 0, 0);

        for (let i = 6; i >= 0; i--) {
          const date = new Date(now);
          date.setDate(now.getDate() - i);
          labels.push(date.toLocaleDateString('en-US', { weekday: 'short' }));
          dateKeys.push(this.toISODate(date) || ''); // Store the actual date for mapping
        }
        break;
    }

    return { startDate, endDate, labels, dateKeys };
  }

  // Helper method to produce 'YYYY-MM-DD' from Date or date-string
  private static toISODate(d: Date | string): string | null {
    const date = typeof d === 'string' ? new Date(d) : d;
    if (Number.isNaN(date.getTime())) return null;
    const y = date.getFullYear();
    const m = `${date.getMonth() + 1}`.padStart(2, '0');
    const day = `${date.getDate()}`.padStart(2, '0');
    return `${y}-${m}-${day}`;
  }

  // ============== GET PDF REPORT ==============
  public static getPdfReport = asyncHandler(async (req: Request, res: Response) => {
    try {
      const { startDate, endDate, timePeriod, year } = req.query;

      // Validate year parameter if provided
      let yearNumber: number | undefined;
      if (year) {
        yearNumber = parseInt(year as string, 10);
        const currentYear = new Date().getFullYear();
        if (isNaN(yearNumber) || yearNumber < 2000 || yearNumber > currentYear + 1) {
          return res
            .status(400)
            .json(
              UniResponse.Error(
                `Invalid year. Must be between 2000 and ${currentYear + 1}.`,
                null,
                400
              )
            );
        }
      }

      // Determine time period: if year is provided, use '1y', otherwise use provided timePeriod or default
      let validTimePeriod: '1d' | '7d' | '30d' | '1y' = '30d';
      if (yearNumber) {
        validTimePeriod = '1y';
      } else if (timePeriod) {
        const timePeriodStr = timePeriod as string;
        if (!['1d', '7d', '30d', '1y'].includes(timePeriodStr)) {
          return res
            .status(400)
            .json(
              UniResponse.Error(
                "Invalid time period. Must be '1d', '7d', '30d', or '1y'.",
                null,
                400
              )
            );
        }
        validTimePeriod = timePeriodStr as '1d' | '7d' | '30d' | '1y';
      }

      const pdfBuffer = await AdminRepository.getPdfReportStream(validTimePeriod, {
        startDate: startDate ? new Date(startDate as string) : undefined,
        endDate: endDate ? new Date(endDate as string) : undefined,
        year: yearNumber,
      });

      // Create reports directory if it doesn't exist
      // Use root-level uploads directory for both production and development
      const baseUploadsDir = path.join(process.cwd(), 'uploads');
      const reportsDir = path.join(baseUploadsDir, 'reports');
      if (!fs.existsSync(reportsDir)) {
        fs.mkdirSync(reportsDir, { recursive: true });
      }

      // Generate unique filename
      const timestamp = new Date().toISOString().split('T')[0];
      const uniqueId = Date.now() + '-' + Math.round(Math.random() * 1e9);
      const periodSuffix =
        validTimePeriod === '1y'
          ? `year-${yearNumber || new Date().getFullYear()}`
          : validTimePeriod;
      const filename = `quick-connect-report-${periodSuffix}-${timestamp}-${uniqueId}.pdf`;
      const filePath = path.join(reportsDir, filename);

      // Save PDF buffer to file
      fs.writeFileSync(filePath, pdfBuffer);

      // Construct download URL
      // Use req.get('host') to include port number when needed
      const baseUrl = process.env.BASE_URL || `${req.protocol}://${req.get('host')}`;
      const downloadUrl = `${baseUrl}/uploads/reports/${filename}`;

      // Return JSON response with download link
      return res.json(
        UniResponse.Success(
          'PDF report generated successfully',
          {
            downloadUrl,
            filename,
            timePeriod: validTimePeriod === '1y' ? 'yearly' : validTimePeriod,
            year: yearNumber || null,
            generatedAt: new Date().toISOString(),
          },
          200
        )
      );
    } catch (error: any) {
      console.error('PDF generation failed:', error);
      res
        .status(500)
        .json(
          UniResponse.Error(
            humanizeClientError(
              error,
              'We could not generate the PDF report. Please try again.'
            ),
            null,
            500
          )
        );
    }
  });

  // ============== TOGGLE QR CODE STATUS ==============
  public static toggleQRCodeStatus = asyncHandler(
    async (req: Request, res: Response) => {
      try {
        const { id } = req.params;

        // Validate ID parameter
        if (!id) {
          return res.status(400).json(UniResponse.Error('QR code ID is required', 400));
        }

        // Find the QR code by ID
        const qrCode = await QRCodeModel.findById(id);
        if (!qrCode) {
          return res.status(404).json(UniResponse.Error('QR code not found', 404));
        }

        // Toggle the status
        const newStatus = qrCode.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE';
        const updatedQRCode = await QRCodeModel.findByIdAndUpdate(
          id,
          { status: newStatus },
          { new: true } // Return the updated document
        );

        if (!updatedQRCode) {
          return res
            .status(404)
            .json(UniResponse.Error('Failed to update QR code status', 404));
        }

        return res.json(
          UniResponse.Success(
            'QR code status updated successfully',
            {
              qrCodeId: id,
              previousStatus: qrCode.status,
              newStatus: updatedQRCode.status,
            },
            200
          )
        );
      } catch (error: any) {
        console.error('Error toggling QR code status:', error);
        return res
          .status(500)
          .json(
            UniResponse.Error(
              humanizeClientError(
                error,
                'We could not update the QR code status. Please try again.'
              ),
              null,
              500
            )
          );
      }
    }
  );

  // ============== TOGGLE ADMIN NOTIFICATIONS ==============
  public static toggleAdminNotifications = asyncHandler(
    async (req: Request, res: Response) => {
      try {
        const userId = (req as any).user?.userId;

        if (!userId) {
          return res
            .status(401)
            .json(UniResponse.Error('User not authenticated', null, 401));
        }

        // Find the admin user
        const admin = await UserModel.findById(userId).select(
          'adminNotificationsEnabled role'
        );

        if (!admin) {
          return res.status(404).json(UniResponse.Error('User not found', null, 404));
        }

        // Verify user is an admin
        if (admin.role !== 'ADMIN') {
          return res
            .status(403)
            .json(
              UniResponse.Error('Access denied. Admin privileges required', null, 403)
            );
        }

        // Toggle the admin notifications preference
        const newState = !(admin.adminNotificationsEnabled ?? true);
        const updatedAdmin = await UserModel.findByIdAndUpdate(
          userId,
          { adminNotificationsEnabled: newState },
          { new: true }
        ).select('adminNotificationsEnabled');

        if (!updatedAdmin) {
          return res
            .status(404)
            .json(
              UniResponse.Error(
                'Failed to update admin notification preference',
                null,
                404
              )
            );
        }

        return res.json(
          UniResponse.Success(
            `Admin notifications ${newState ? 'enabled' : 'disabled'} successfully`,
            {
              adminNotificationsEnabled: updatedAdmin.adminNotificationsEnabled ?? true,
            },
            200
          )
        );
      } catch (error: any) {
        console.error('Error toggling admin notifications:', error);
        return res
          .status(500)
          .json(
            UniResponse.Error(
              humanizeClientError(
                error,
                'We could not update notification settings. Please try again.'
              ),
              null,
              500
            )
          );
      }
    }
  );

  // ============== GET ADMIN NOTIFICATION STATUS ==============
  public static getAdminNotificationStatus = asyncHandler(
    async (req: Request, res: Response) => {
      try {
        const userId = (req as any).user?.userId;

        if (!userId) {
          return res
            .status(401)
            .json(UniResponse.Error('User not authenticated', null, 401));
        }

        // Find the admin user
        const admin = await UserModel.findById(userId).select(
          'adminNotificationsEnabled role'
        );

        if (!admin) {
          return res.status(404).json(UniResponse.Error('User not found', null, 404));
        }

        // Verify user is an admin
        if (admin.role !== 'ADMIN') {
          return res
            .status(403)
            .json(
              UniResponse.Error('Access denied. Admin privileges required', null, 403)
            );
        }

        return res.json(
          UniResponse.Success(
            'Admin notification status retrieved successfully',
            {
              adminNotificationsEnabled: admin.adminNotificationsEnabled ?? true,
            },
            200
          )
        );
      } catch (error: any) {
        console.error('Error getting admin notification status:', error);
        return res
          .status(500)
          .json(
            UniResponse.Error(
              humanizeClientError(
                error,
                'We could not load notification status. Please try again.'
              ),
              null,
              500
            )
          );
      }
    }
  );

  // ============== GET ALL ADMIN NOTIFICATIONS ==============
  public static getAllAdminNotifications = asyncHandler(
    async (req: Request, res: Response) => {
      try {
        const userId = (req as any).user?.userId;

        if (!userId) {
          return res
            .status(401)
            .json(UniResponse.Error('User not authenticated', null, 401));
        }

        // Find the admin user
        const admin = await UserModel.findById(userId).select('role');

        if (!admin) {
          return res.status(404).json(UniResponse.Error('User not found', null, 404));
        }

        // Verify user is an admin
        if (admin.role !== 'ADMIN') {
          return res
            .status(403)
            .json(
              UniResponse.Error('Access denied. Admin privileges required', null, 403)
            );
        }

        // Get query parameters
        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 10;
        const is_read = req.query.is_read as string | undefined;
        const type = req.query.type as string | undefined;
        const user_id = req.query.user_id as string | undefined;

        // Build filters
        const filters: {
          is_read?: boolean;
          type?: string;
          user_id?: string;
        } = {};

        if (is_read !== undefined) {
          filters.is_read = is_read === 'true';
        }
        if (type) {
          filters.type = type;
        }
        if (user_id) {
          filters.user_id = user_id;
        }

        // Get all notifications
        const result = await NotificationService.getAllNotifications(
          page,
          limit,
          filters
        );

        return res.json(
          UniResponse.Success('All notifications retrieved successfully', result, 200)
        );
      } catch (error: any) {
        console.error('Error getting all admin notifications:', error);
        return res
          .status(500)
          .json(
            UniResponse.Error(
              humanizeClientError(
                error,
                'We could not load notifications. Please try again.'
              ),
              null,
              500
            )
          );
      }
    }
  );

  // ============== GET USER BEHAVIOR PDF REPORT ==============
  public static getUserBehaviorPdfReport = asyncHandler(
    async (req: Request, res: Response) => {
      try {
        const { startDate, endDate, timePeriod } = req.query;

        // Validate time period parameter
        const validTimePeriod = (timePeriod as string) || '30d';
        if (!['1d', '7d', '30d'].includes(validTimePeriod)) {
          return res
            .status(400)
            .json(
              UniResponse.Error(
                "Invalid time period. Must be '1d', '7d', or '30d'.",
                null,
                400
              )
            );
        }

        const pdfBuffer = await AdminRepository.getUserBehaviorPdfReportStream(
          validTimePeriod as '1d' | '7d' | '30d',
          {
            startDate: startDate ? new Date(startDate as string) : undefined,
            endDate: endDate ? new Date(endDate as string) : undefined,
          }
        );

        // Create reports directory if it doesn't exist
        // Use root-level uploads directory for both production and development
        const baseUploadsDir = path.join(process.cwd(), 'uploads');
        const reportsDir = path.join(baseUploadsDir, 'reports');
        if (!fs.existsSync(reportsDir)) {
          fs.mkdirSync(reportsDir, { recursive: true });
        }

        // Generate unique filename
        const timestamp = new Date().toISOString().split('T')[0];
        const uniqueId = Date.now() + '-' + Math.round(Math.random() * 1e9);
        const filename = `user-behavior-report-${validTimePeriod}-${timestamp}-${uniqueId}.pdf`;
        const filePath = path.join(reportsDir, filename);

        // Save PDF buffer to file
        fs.writeFileSync(filePath, pdfBuffer);

        // Construct download URL
        // Use req.get('host') to include port number when needed
        const baseUrl = process.env.BASE_URL || `${req.protocol}://${req.get('host')}`;
        const downloadUrl = `${baseUrl}/uploads/reports/${filename}`;

        // Return JSON response with download link
        return res.json(
          UniResponse.Success(
            'User behavior PDF report generated successfully',
            {
              downloadUrl,
              filename,
              timePeriod: validTimePeriod,
              generatedAt: new Date().toISOString(),
            },
            200
          )
        );
      } catch (error: any) {
        console.error('User behavior PDF generation failed:', error);
        res
          .status(500)
          .json(
            UniResponse.Error(
              humanizeClientError(
                error,
                'We could not generate the user behavior PDF report. Please try again.'
              ),
              null,
              500
            )
          );
      }
    }
  );

  // =========== TOP QRCODES ================
  private static getTopQrcodes = async (limit = 10) => {
    return await ScanModel.aggregate([
      {
        $group: {
          _id: '$qrcode_id',
          totalScans: { $sum: 1 },
        },
      },
      {
        $lookup: {
          from: 'qrcodes',
          localField: '_id',
          foreignField: '_id',
          as: 'qrcode',
        },
      },
      { $unwind: '$qrcode' },
      { $sort: { topScans: -1 } },
      { $limit: limit },
    ]);
  };

  // ======== TOP PERFOMAING QRCODES ================
  private static getTopPerformingQrcodes = async (limit = 10) => {
    return await ScanModel.aggregate([
      {
        $group: {
          _id: '$qrcode_id',
          totalScans: { $sum: 1 },
        },
      },
      {
        $lookup: {
          from: 'qrcodes',
          localField: '_id',
          foreignField: '_id',
          as: 'qrcode',
        },
      },
      { $unwind: '$qrcode' },
      { $sort: { totalScans: -1 } },
      { $limit: limit },
    ]);
  };

  // PDF Generation constants
  private static readonly PDF_BRAND_BLUE = '#1E3A8A';
  private static readonly PDF_BRAND_LIGHT_BLUE = '#3B82F6';
  private static readonly PDF_BRAND_BG_BLUE = '#EFF6FF';
  private static readonly PDF_MARGIN_TOP = 60;
  private static readonly PDF_MARGIN_BOTTOM = 60;
  private static readonly PDF_MARGIN_LEFT = 50;
  private static readonly PDF_MARGIN_RIGHT = 50;
  private static readonly PDF_HEADER_HEIGHT = 80;
  private static readonly PDF_FOOTER_HEIGHT = 40;
  private static readonly PDF_FONT_TITLE = 24;
  private static readonly PDF_FONT_SECTION = 16;
  private static readonly PDF_FONT_SUBSECTION = 12;
  private static readonly PDF_FONT_BODY = 10;
  private static readonly PDF_FONT_TABLE = 8;
  private static readonly PDF_FONT_SMALL = 7;

  /**
   * Load logo image with fallback
   */
  private static loadLogo(): Buffer | null {
    try {
      const paths = [
        resolve(__dirname, '../../../uploads/quick-connect.ico'),
        resolve(__dirname, '../../uploads/quick-connect.ico'),
        resolve(process.cwd(), 'uploads/quick-connect.ico'),
      ];
      for (const logoPath of paths) {
        if (existsSync(logoPath)) {
          return readFileSync(logoPath);
        }
      }
    } catch (error) {
      console.warn('Logo file not found, using text-only branding');
    }
    return null;
  }

  /**
   * Draw page header with logo and branding
   */
  private static drawPdfHeader(
    doc: any,
    pageNumber: number,
    totalPages: number,
    reportType: string,
    isFirstPage: boolean = false
  ) {
    const logo = this.loadLogo();
    const currentY = doc.y;

    // Blue header background
    doc.rect(0, 0, doc.page.width, this.PDF_HEADER_HEIGHT).fill(this.PDF_BRAND_BLUE);

    // Logo
    let logoX = this.PDF_MARGIN_LEFT;
    if (logo) {
      try {
        doc.image(logo, logoX, 20, {
          width: 40,
          height: 40,
          fit: [40, 40],
        });
        logoX += 55;
      } catch (error) {
        logoX = this.PDF_MARGIN_LEFT;
      }
    }

    // Title
    doc
      .fillColor('#FFFFFF')
      .fontSize(this.PDF_FONT_TITLE)
      .font('Helvetica-Bold')
      .text('Quick Connect', logoX, 25, {
        width: doc.page.width - logoX - this.PDF_MARGIN_RIGHT,
      })
      .fontSize(this.PDF_FONT_SUBSECTION)
      .font('Helvetica')
      .text(reportType, logoX, 50, {
        width: doc.page.width - logoX - this.PDF_MARGIN_RIGHT,
      });

    // Generation timestamp (right aligned)
    const genTime = new Date().toLocaleString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
    doc
      .fontSize(this.PDF_FONT_SMALL)
      .text(`Generated: ${genTime}`, this.PDF_MARGIN_LEFT, 55, {
        width: doc.page.width - this.PDF_MARGIN_LEFT - this.PDF_MARGIN_RIGHT,
        align: 'right',
      });

    // Reset color and position
    doc.fillColor('#000000');
    doc.y = this.PDF_HEADER_HEIGHT + 20;
  }

  /**
   * Draw page footer with branding and page numbers
   */
  private static drawPdfFooter(doc: any, pageNumber: number, totalPages: number) {
    const footerY = doc.page.height - this.PDF_FOOTER_HEIGHT;

    // Footer line
    doc
      .strokeColor('#E5E7EB')
      .lineWidth(1)
      .moveTo(this.PDF_MARGIN_LEFT, footerY)
      .lineTo(doc.page.width - this.PDF_MARGIN_RIGHT, footerY)
      .stroke();

    // Page number
    doc
      .fontSize(this.PDF_FONT_SMALL)
      .font('Helvetica')
      .fillColor('#6B7280')
      .text(`Page ${pageNumber} of ${totalPages}`, this.PDF_MARGIN_LEFT, footerY + 10, {
        width: doc.page.width - this.PDF_MARGIN_LEFT - this.PDF_MARGIN_RIGHT,
        align: 'center',
      });

    // Company branding
    doc.text(
      'Quick Connect - QR Code Management System',
      this.PDF_MARGIN_LEFT,
      footerY + 25,
      {
        width: doc.page.width - this.PDF_MARGIN_LEFT - this.PDF_MARGIN_RIGHT,
        align: 'center',
      }
    );
  }

  /**
   * Generate QR Code PDF Report
   * GET /api/admin/qrcode-pdf-report
   */
  public static getQrCodePdfReport = asyncHandler(
    async (req: Request, res: Response) => {
      try {
        const { mode, qrcodeId, startDate, endDate } = req.query;

        // Validate mode parameter
        const validMode = (mode as string) || 'on-demand';
        if (!['on-demand', 'daily', 'custom'].includes(validMode)) {
          return res
            .status(400)
            .json(
              UniResponse.Error(
                "Invalid mode. Must be 'on-demand', 'daily', or 'custom'.",
                null,
                400
              )
            );
        }

        // Validate date parameters for custom mode
        if (validMode === 'custom') {
          if (!startDate || !endDate) {
            return res
              .status(400)
              .json(
                UniResponse.Error(
                  'startDate and endDate are required for custom mode',
                  null,
                  400
                )
              );
          }
          const start = new Date(startDate as string);
          const end = new Date(endDate as string);
          if (isNaN(start.getTime()) || isNaN(end.getTime())) {
            return res
              .status(400)
              .json(
                UniResponse.Error(
                  'Invalid date format. Use ISO format (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss)',
                  null,
                  400
                )
              );
          }
          if (start > end) {
            return res
              .status(400)
              .json(UniResponse.Error('startDate must be before endDate', null, 400));
          }
        }

        // Fetch QR code data
        const reportData = await AdminRepository.getQrCodeReportData(
          validMode as 'on-demand' | 'daily' | 'custom',
          qrcodeId as string,
          startDate ? new Date(startDate as string) : undefined,
          endDate ? new Date(endDate as string) : undefined
        );

        // Create PDF document
        const doc = new PDFDocument({
          size: 'A4',
          margins: {
            top: this.PDF_MARGIN_TOP,
            bottom: this.PDF_MARGIN_BOTTOM,
            left: this.PDF_MARGIN_LEFT,
            right: this.PDF_MARGIN_RIGHT,
          },
        });

        // Set report type
        const reportType =
          validMode === 'daily'
            ? 'Daily QR Code Summary'
            : validMode === 'custom'
              ? 'Custom QR Code Report'
              : 'QR Code Export Report';

        // Create uploads directory if it doesn't exist
        // Use root-level uploads directory for both production and development
        const uploadDir = path.join(process.cwd(), 'uploads');
        if (!fs.existsSync(uploadDir)) {
          fs.mkdirSync(uploadDir, { recursive: true });
        }

        // Generate unique filename
        const timestamp = Date.now();
        const filename = `qrcode-report-${validMode}-${new Date().toISOString().split('T')[0]}-${timestamp}.pdf`;
        const filePath = path.join(uploadDir, filename);

        // Create write stream to save PDF
        const writeStream = fs.createWriteStream(filePath);
        doc.pipe(writeStream);

        // Track page numbers
        let currentPage = 1;
        const addPageWithHeader = (isFirstPage: boolean = false) => {
          if (!isFirstPage) {
            doc.addPage();
            currentPage++;
          }
          const pageRange = doc.bufferedPageRange();
          const totalPages = pageRange.count;
          this.drawPdfHeader(doc, currentPage, totalPages, reportType, isFirstPage);
        };

        // First page
        addPageWithHeader(true);
        const pageRange = doc.bufferedPageRange();
        let totalPages = pageRange.count;

        // Title Page Section
        doc
          .fontSize(this.PDF_FONT_TITLE)
          .font('Helvetica-Bold')
          .fillColor(this.PDF_BRAND_BLUE)
          .text('QR Code Report', this.PDF_MARGIN_LEFT, doc.y, {
            underline: true,
          });
        doc.moveDown(1.5);

        // Executive Summary Card
        const cardY = doc.y;
        const cardHeight = 100;
        doc
          .rect(
            this.PDF_MARGIN_LEFT,
            cardY,
            doc.page.width - this.PDF_MARGIN_LEFT - this.PDF_MARGIN_RIGHT,
            cardHeight
          )
          .fill(this.PDF_BRAND_BG_BLUE)
          .stroke(this.PDF_BRAND_LIGHT_BLUE);

        doc
          .fontSize(this.PDF_FONT_SUBSECTION)
          .font('Helvetica-Bold')
          .fillColor(this.PDF_BRAND_BLUE)
          .text('Executive Summary', this.PDF_MARGIN_LEFT + 15, cardY + 10);

        doc
          .fontSize(this.PDF_FONT_BODY)
          .font('Helvetica')
          .fillColor('#000000')
          .text(
            `Total QR Codes: ${reportData.totalQrCodes}`,
            this.PDF_MARGIN_LEFT + 15,
            cardY + 35
          )
          .text(
            `Active QR Codes: ${reportData.activeQrCodes}`,
            this.PDF_MARGIN_LEFT + 200,
            cardY + 35
          )
          .text(
            `Total Scans: ${reportData.totalScans}`,
            this.PDF_MARGIN_LEFT + 15,
            cardY + 55
          );

        const dateRangeStr = `${reportData.dateRange.startDate.toLocaleDateString()} - ${reportData.dateRange.endDate.toLocaleDateString()}`;
        doc
          .text(`Date Range: ${dateRangeStr}`, this.PDF_MARGIN_LEFT + 200, cardY + 55)
          .text(`Report Mode: ${validMode}`, this.PDF_MARGIN_LEFT + 15, cardY + 75);

        doc.y = cardY + cardHeight + 30;

        // Top QR Codes Section
        if (reportData.qrCodes.length > 0) {
          doc
            .fontSize(this.PDF_FONT_SECTION)
            .font('Helvetica-Bold')
            .fillColor(this.PDF_BRAND_BLUE)
            .text('Top QR Codes by Scan Count', this.PDF_MARGIN_LEFT, doc.y, {
              underline: true,
            });
          doc.moveDown(1);

          // Table header
          const tableTop = doc.y;
          const colWidths = [200, 80, 80, 150];
          const rowHeight = 20;

          doc
            .fontSize(this.PDF_FONT_TABLE)
            .font('Helvetica-Bold')
            .fillColor('#FFFFFF')
            .rect(
              this.PDF_MARGIN_LEFT,
              tableTop,
              colWidths[0] + colWidths[1] + colWidths[2] + colWidths[3],
              rowHeight
            )
            .fill(this.PDF_BRAND_BLUE);

          let x = this.PDF_MARGIN_LEFT + 5;
          doc.text('Title', x, tableTop + 5, { width: colWidths[0] - 10 });
          x += colWidths[0];
          doc.text('Type', x, tableTop + 5, { width: colWidths[1] - 10 });
          x += colWidths[1];
          doc.text('Scans', x, tableTop + 5, { width: colWidths[2] - 10 });
          x += colWidths[2];
          doc.text('Status', x, tableTop + 5, { width: colWidths[3] - 10 });

          // Table rows
          doc.font('Helvetica').fillColor('#000000');
          let tableY = tableTop + rowHeight;
          let rowIndex = 0;

          for (const qrCode of reportData.qrCodes.slice(0, 20)) {
            // Limit to 20 for PDF
            if (tableY + rowHeight > doc.page.height - this.PDF_FOOTER_HEIGHT - 40) {
              // Draw footer before adding new page
              this.drawPdfFooter(doc, currentPage, totalPages);
              addPageWithHeader(false);
              const pageRange = doc.bufferedPageRange();
              totalPages = pageRange.count;
              tableY = doc.y;
              // Redraw header row
              doc
                .fontSize(this.PDF_FONT_TABLE)
                .font('Helvetica-Bold')
                .fillColor('#FFFFFF')
                .rect(
                  this.PDF_MARGIN_LEFT,
                  tableY - rowHeight,
                  colWidths[0] + colWidths[1] + colWidths[2] + colWidths[3],
                  rowHeight
                )
                .fill(this.PDF_BRAND_BLUE);
              x = this.PDF_MARGIN_LEFT + 5;
              doc.text('Title', x, tableY - rowHeight + 5, {
                width: colWidths[0] - 10,
              });
              x += colWidths[0];
              doc.text('Type', x, tableY - rowHeight + 5, { width: colWidths[1] - 10 });
              x += colWidths[1];
              doc.text('Scans', x, tableY - rowHeight + 5, {
                width: colWidths[2] - 10,
              });
              x += colWidths[2];
              doc.text('Status', x, tableY - rowHeight + 5, {
                width: colWidths[3] - 10,
              });
              doc.font('Helvetica').fillColor('#000000');
            }

            // Alternate row color
            if (rowIndex % 2 === 0) {
              doc
                .rect(
                  this.PDF_MARGIN_LEFT,
                  tableY,
                  colWidths[0] + colWidths[1] + colWidths[2] + colWidths[3],
                  rowHeight
                )
                .fill('#F8FAFC');
            }

            x = this.PDF_MARGIN_LEFT + 5;
            doc.text(qrCode.title || 'Untitled', x, tableY + 5, {
              width: colWidths[0] - 10,
            });
            x += colWidths[0];
            doc.text(qrCode.type || 'N/A', x, tableY + 5, { width: colWidths[1] - 10 });
            x += colWidths[1];
            doc.text(String(qrCode.scan_count || 0), x, tableY + 5, {
              width: colWidths[2] - 10,
            });
            x += colWidths[2];
            doc.text(qrCode.status || 'N/A', x, tableY + 5, {
              width: colWidths[3] - 10,
            });

            tableY += rowHeight;
            rowIndex++;
          }

          doc.y = tableY + 20;
        }

        // Recent Scan Logs Section
        if (reportData.scans.length > 0) {
          if (doc.y > doc.page.height - this.PDF_FOOTER_HEIGHT - 100) {
            this.drawPdfFooter(doc, currentPage, totalPages);
            addPageWithHeader(false);
            const pageRange = doc.bufferedPageRange();
            totalPages = pageRange.count;
          }

          doc
            .fontSize(this.PDF_FONT_SECTION)
            .font('Helvetica-Bold')
            .fillColor(this.PDF_BRAND_BLUE)
            .text('Recent Scan Activity', this.PDF_MARGIN_LEFT, doc.y, {
              underline: true,
            });
          doc.moveDown(1);

          // Scan logs table
          const scanTableTop = doc.y;
          const scanColWidths = [150, 150, 100, 150];
          const scanRowHeight = 18;

          doc
            .fontSize(this.PDF_FONT_TABLE)
            .font('Helvetica-Bold')
            .fillColor('#FFFFFF')
            .rect(
              this.PDF_MARGIN_LEFT,
              scanTableTop,
              scanColWidths[0] + scanColWidths[1] + scanColWidths[2] + scanColWidths[3],
              scanRowHeight
            )
            .fill(this.PDF_BRAND_BLUE);

          let scanX = this.PDF_MARGIN_LEFT + 5;
          doc.text('QR Code ID', scanX, scanTableTop + 5, {
            width: scanColWidths[0] - 10,
          });
          scanX += scanColWidths[0];
          doc.text('Scanned By', scanX, scanTableTop + 5, {
            width: scanColWidths[1] - 10,
          });
          scanX += scanColWidths[1];
          doc.text('Anonymous', scanX, scanTableTop + 5, {
            width: scanColWidths[2] - 10,
          });
          scanX += scanColWidths[2];
          doc.text('Date', scanX, scanTableTop + 5, { width: scanColWidths[3] - 10 });

          doc.font('Helvetica').fillColor('#000000');
          let scanTableY = scanTableTop + scanRowHeight;
          let scanRowIndex = 0;

          for (const scan of reportData.scans.slice(0, 30)) {
            // Limit to 30 scans
            if (
              scanTableY + scanRowHeight >
              doc.page.height - this.PDF_FOOTER_HEIGHT - 40
            ) {
              this.drawPdfFooter(doc, currentPage, totalPages);
              addPageWithHeader(false);
              const pageRange = doc.bufferedPageRange();
              totalPages = pageRange.count;
              scanTableY = doc.y;
              // Redraw header
              doc
                .fontSize(this.PDF_FONT_TABLE)
                .font('Helvetica-Bold')
                .fillColor('#FFFFFF')
                .rect(
                  this.PDF_MARGIN_LEFT,
                  scanTableY - scanRowHeight,
                  scanColWidths[0] +
                    scanColWidths[1] +
                    scanColWidths[2] +
                    scanColWidths[3],
                  scanRowHeight
                )
                .fill(this.PDF_BRAND_BLUE);
              scanX = this.PDF_MARGIN_LEFT + 5;
              doc.text('QR Code ID', scanX, scanTableY - scanRowHeight + 5, {
                width: scanColWidths[0] - 10,
              });
              scanX += scanColWidths[0];
              doc.text('Scanned By', scanX, scanTableY - scanRowHeight + 5, {
                width: scanColWidths[1] - 10,
              });
              scanX += scanColWidths[1];
              doc.text('Anonymous', scanX, scanTableY - scanRowHeight + 5, {
                width: scanColWidths[2] - 10,
              });
              scanX += scanColWidths[2];
              doc.text('Date', scanX, scanTableY - scanRowHeight + 5, {
                width: scanColWidths[3] - 10,
              });
              doc.font('Helvetica').fillColor('#000000');
            }

            if (scanRowIndex % 2 === 0) {
              doc
                .rect(
                  this.PDF_MARGIN_LEFT,
                  scanTableY,
                  scanColWidths[0] +
                    scanColWidths[1] +
                    scanColWidths[2] +
                    scanColWidths[3],
                  scanRowHeight
                )
                .fill('#F8FAFC');
            }

            scanX = this.PDF_MARGIN_LEFT + 5;
            // Use populated qrcode_data if available, otherwise fallback to ID
            const qrCodeTitle =
              scan.qrcode_data?.title ||
              scan.qrcode_id?.toString().substring(0, 12) ||
              'N/A';
            doc.text(qrCodeTitle, scanX, scanTableY + 4, {
              width: scanColWidths[0] - 10,
            });
            scanX += scanColWidths[0];
            // Use properly populated scanned_by data
            const scannedBy = scan.scanned_by
              ? scan.scanned_by.email ||
                `${scan.scanned_by.first_name || ''} ${scan.scanned_by.last_name || ''}`.trim() ||
                'User'
              : scan.is_anonymous
                ? 'Anonymous'
                : 'N/A';
            doc.text(scannedBy, scanX, scanTableY + 4, {
              width: scanColWidths[1] - 10,
            });
            scanX += scanColWidths[1];
            doc.text(scan.is_anonymous ? 'Yes' : 'No', scanX, scanTableY + 4, {
              width: scanColWidths[2] - 10,
            });
            scanX += scanColWidths[2];
            const scanDate = scan.createdAt
              ? new Date(scan.createdAt).toLocaleDateString()
              : 'N/A';
            doc.text(scanDate, scanX, scanTableY + 4, { width: scanColWidths[3] - 10 });

            scanTableY += scanRowHeight;
            scanRowIndex++;
          }

          doc.y = scanTableY + 20;
        }

        // Draw final footer
        const finalPageRange = doc.bufferedPageRange();
        totalPages = finalPageRange.count;
        this.drawPdfFooter(doc, currentPage, totalPages);

        // Finalize PDF and wait for it to be written
        doc.end();

        // Wait for the PDF to be fully written to disk
        await new Promise<void>((resolve, reject) => {
          writeStream.on('finish', () => {
            resolve();
          });
          writeStream.on('error', error => {
            reject(error);
          });
        });

        // Construct download URL
        const protocol = req.protocol;
        const host = req.get('host');
        const downloadUrl = `${protocol}://${host}/uploads/${filename}`;

        // Return success response with download URL
        const response = UniResponse.Success(
          'QR Code PDF Report generated successfully',
          {
            downloadUrl,
            filename,
            reportType,
            totalQrCodes: reportData.totalQrCodes,
            totalScans: reportData.totalScans,
            activeQrCodes: reportData.activeQrCodes,
            dateRange: {
              startDate: reportData.dateRange.startDate.toISOString(),
              endDate: reportData.dateRange.endDate.toISOString(),
            },
          },
          200
        );
        return res.status(response.code).json(response);
      } catch (error: any) {
        console.error('QR Code PDF generation failed:', error);
        if (!res.headersSent) {
          res
            .status(500)
            .json(
              UniResponse.Error(
                humanizeClientError(
                  error,
                  'We could not generate the QR code PDF report. Please try again.'
                ),
                null,
                500
              )
            );
        }
      }
    }
  );
}
