import mongoose from 'mongoose';
import QRCodeModel from '../../models/QrCode';
import ScanModel from '../../models/Scan';
import NotificationModel from '../../models/Notification';

export class DashboardRepository {
  /**
   * Get count of active QR codes for a user
   */
  static async getActiveQRCodesCount(userId: mongoose.Types.ObjectId): Promise<number> {
    return await QRCodeModel.countDocuments({
      created_by: userId,
      status: 'ACTIVE',
      isDelete: false,
    });
  }

  /**
   * Get total scans count for user's QR codes in the last 30 days
   */
  static async getTotalScansLast30Days(
    userId: mongoose.Types.ObjectId,
    thirtyDaysAgo: Date
  ): Promise<number> {
    const result = await ScanModel.aggregate([
      {
        $lookup: {
          from: 'qrcodes',
          localField: 'qrcode_id',
          foreignField: '_id',
          as: 'qrcode',
        },
      },
      {
        $match: {
          'qrcode.created_by': userId,
        },
      },
      {
        $count: 'totalScans',
      },
    ]);

    return result.length > 0 ? result[0].totalScans : 0;
  }

  /**
   * Get count of QR codes expiring within 7 days
   */
  static async getExpiringSoonCount(
    userId: mongoose.Types.ObjectId,
    now: Date,
    sevenDaysFromNow: Date
  ): Promise<number> {
    return await QRCodeModel.countDocuments({
      created_by: userId,
      status: 'ACTIVE',
      isDelete: false,
      expired_at: {
        $gte: now,
        $lte: sevenDaysFromNow,
      },
    });
  }

  /**
   * Get count of unread notifications for user's QR codes
   */
  static async getUnreadNotificationsCount(
    userId: mongoose.Types.ObjectId
  ): Promise<number> {
    const userQRCodeIds = await QRCodeModel.find(
      { created_by: userId },
      { _id: 1 }
    ).distinct('_id');

    return await NotificationModel.countDocuments({
      qrcode_id: { $in: userQRCodeIds },
      is_read: false,
    });
  }

  /**
   * Get user's QR code IDs
   */
  static async getUserQRCodeIds(userId: mongoose.Types.ObjectId): Promise<any[]> {
    return await QRCodeModel.find({ created_by: userId }, { _id: 1 }).distinct('_id');
  }

  /**
   * Get QR codes grouped by type for a user
   */
  static async getQRCodesByType(userId: mongoose.Types.ObjectId): Promise<any[]> {
    return await QRCodeModel.aggregate([
      {
        $match: {
          created_by: userId,
          isDelete: false,
        },
      },
      {
        $group: {
          _id: '$type',
          count: { $sum: 1 },
        },
      },
    ]);
  }

  /**
   * Get scans grouped by day for the last 30 days
   */
  static async getScansByDay(userQRCodes: any[], thirtyDaysAgo: Date): Promise<any[]> {
    return await ScanModel.aggregate([
      {
        $match: {
          qrcode_id: { $in: userQRCodes },
          createdAt: { $gte: thirtyDaysAgo },
          scan_status: 'SUCCESS',
        },
      },
      {
        $group: {
          _id: {
            $dateToString: {
              format: '%Y-%m-%d',
              date: '$createdAt',
            },
          },
          count: { $sum: 1 },
        },
      },
      {
        $sort: { _id: 1 },
      },
    ]);
  }

  /**
   * Get top 5 most scanned QR codes
   */
  static async getTopScannedQRCodes(userQRCodes: any[]): Promise<any[]> {
    return await ScanModel.aggregate([
      {
        $match: {
          qrcode_id: { $in: userQRCodes },
          scan_status: 'SUCCESS',
        },
      },
      {
        $group: {
          _id: '$qrcode_id',
          scanCount: { $sum: 1 },
        },
      },
      {
        $lookup: {
          from: 'qrcodes',
          localField: '_id',
          foreignField: '_id',
          as: 'qrcode',
        },
      },
      {
        $unwind: '$qrcode',
      },
      {
        $project: {
          title: '$qrcode.title',
          type: '$qrcode.type',
          scanCount: 1,
        },
      },
      {
        $sort: { scanCount: -1 },
      },
      {
        $limit: 5,
      },
    ]);
  }

  /**
   * Get recent scan activity (last 10 scans)
   */
  static async getRecentActivity(userQRCodes: any[]): Promise<any[]> {
    return await ScanModel.find({
      qrcode_id: { $in: userQRCodes },
    })
      .populate('qrcode_id', 'title type')
      .sort({ createdAt: -1 })
      .limit(10)
      .select('scan_location createdAt scan_status');
  }
}
