import mongoose from 'mongoose';
import { DashboardRepository } from './dashboardRepository';

export interface DashboardCardsData {
  activeQRCodes: {
    count: number;
    label: string;
    description: string;
  };
  totalScans: {
    count: number;
    label: string;
    description: string;
  };
  expiringSoon: {
    count: number;
    label: string;
    description: string;
  };
  notifications: {
    count: number;
    label: string;
    description: string;
  };
}

export interface DashboardAnalyticsData {
  qrCodesByType: any[];
  scansByDay: any[];
  topScannedQRCodes: any[];
  recentActivity: any[];
}

export class DashboardService {
  /**
   * Get dashboard cards data for a user
   */
  static async getDashboardCards(userId: string): Promise<DashboardCardsData> {
    const userObjectId = new mongoose.Types.ObjectId(userId);

    // Calculate date ranges
    const now = new Date();
    const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
    const sevenDaysFromNow = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

    // Execute all queries in parallel for better performance
    const [activeQRCodes, totalScans, expiringSoon, unreadNotifications] =
      await Promise.all([
        DashboardRepository.getActiveQRCodesCount(userObjectId),
        DashboardRepository.getTotalScansLast30Days(userObjectId, thirtyDaysAgo),
        DashboardRepository.getExpiringSoonCount(userObjectId, now, sevenDaysFromNow),
        DashboardRepository.getUnreadNotificationsCount(userObjectId),
      ]);

    console.log(totalScans);

    return {
      activeQRCodes: {
        count: activeQRCodes,
        label: 'Active QR Codes',
        description: 'Total created',
      },
      totalScans: {
        count: totalScans,
        label: 'Total Scans',
        description: 'Last 30 days',
      },
      expiringSoon: {
        count: expiringSoon,
        label: 'Expiring Soon',
        description: 'Within 7 days',
      },
      notifications: {
        count: unreadNotifications,
        label: 'Notifications',
        description: 'Unread',
      },
    };
  }

  /**
   * Get detailed dashboard analytics for a user
   */
  static async getDashboardAnalytics(userId: string): Promise<DashboardAnalyticsData> {
    const userObjectId = new mongoose.Types.ObjectId(userId);

    // Calculate date ranges
    const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

    // Get user's QR codes first
    const userQRCodes = await DashboardRepository.getUserQRCodeIds(userObjectId);

    // Execute all analytics queries in parallel
    const [qrCodesByType, scansByDay, topScannedQRCodes, recentActivity] =
      await Promise.all([
        DashboardRepository.getQRCodesByType(userObjectId),
        DashboardRepository.getScansByDay(userQRCodes, thirtyDaysAgo),
        DashboardRepository.getTopScannedQRCodes(userQRCodes),
        DashboardRepository.getRecentActivity(userQRCodes),
      ]);

    return {
      qrCodesByType,
      scansByDay,
      topScannedQRCodes,
      recentActivity,
    };
  }

  /**
   * Validate user authentication
   */
  static validateUser(userId?: string): boolean {
    return !!userId && userId.trim().length > 0;
  }

  /**
   * Get formatted date ranges for dashboard queries
   */
  static getDateRanges() {
    const now = new Date();
    return {
      now,
      thirtyDaysAgo: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000),
      sevenDaysFromNow: new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000),
    };
  }
}
