import admin from 'firebase-admin';

export interface FCMToken {
  token: string;
  deviceType: 'ios' | 'android' | 'web';
}

export interface NotificationAction {
  action: string;
  title: string;
  icon?: string;
}

export interface NotificationPayload {
  title: string;
  message: string;
  icon?: string;
  badge?: string;
  image?: string;
  url?: string;
  tag?: string;
  requireInteraction?: boolean;
  actions?: NotificationAction[];
}

export interface NotificationOptions {
  ttl?: number;
  urgency?: 'very-low' | 'low' | 'normal' | 'high';
  topic?: string;
}

export interface NotificationResult {
  success: boolean;
  message: string;
  error?: any;
}

export interface BulkNotificationResult {
  success: boolean;
  totalSent: number;
  totalFailed: number;
  results: NotificationResult[];
}

export interface SendNotificationParams {
  token: string;
  payload: NotificationPayload;
  options?: NotificationOptions;
}

export interface SendBulkNotificationsParams {
  tokens: string[];
  payload: NotificationPayload;
  options?: NotificationOptions;
}

export interface SendSimpleNotificationParams {
  token: string;
  title: string;
  message: string;
}

export interface SendWithOptionsParams {
  token: string;
  title: string;
  message: string;
  customOptions?: {
    icon?: string;
    image?: string;
    url?: string;
    actions?: NotificationAction[];
    requireInteraction?: boolean;
  };
}

// Helper to mask tokens for logging to avoid leaking sensitive data
function maskToken(token: string): string {
  if (token.length <= 12) return '***';
  return `${token.slice(0, 6)}...${token.slice(-6)}`;
}

export class PushNotificationUtils {
  public static async sendNotification(
    params: SendNotificationParams
  ): Promise<NotificationResult> {
    const { token, payload, options = {} } = params;
    try {
      // Prepare FCM message
      const message: admin.messaging.Message = {
        token,
        notification: {
          title: payload.title,
          body: payload.message,
          imageUrl: payload.image,
        },
        data: {
          url: payload.url || '/',
          tag: payload.tag || 'default',
          icon: payload.icon || '/favicon.ico',
          badge: payload.badge || '/favicon.ico',
          timestamp: Date.now().toString(),
        },
        webpush: payload.actions
          ? {
              notification: {
                requireInteraction: payload.requireInteraction || false,
                actions: payload.actions,
              },
            }
          : undefined,
        android: {
          priority: options.urgency === 'high' ? 'high' : 'normal',
          ttl: options.ttl || 86400000, // 24 hours in milliseconds
          notification: {
            icon: payload.icon || '/favicon.ico',
            imageUrl: payload.image,
            tag: payload.tag,
          },
        },
        apns: {
          payload: {
            aps: {
              badge: 1,
              sound: 'default',
            },
          },
        },
      };

      // Send via Firebase Cloud Messaging
      await admin.messaging().send(message);

      return {
        success: true,
        message: 'Push notification sent successfully',
      };
    } catch (error: any) {
      const sanitizedErrorMsg = error && error.message ? error.message : String(error);

      // Use a minimal logger
      const logFn =
        (global as any).logger && typeof (global as any).logger.error === 'function'
          ? (msg: string, meta?: any) => (global as any).logger.error(msg, meta)
          : (msg: string, meta?: any) => console.error(msg, meta?.message || msg);

      logFn('Push notification send failed', {
        message: sanitizedErrorMsg,
        token: maskToken(token),
      });

      // Handle specific FCM errors
      if (
        error.code === 'messaging/invalid-registration-token' ||
        error.code === 'messaging/registration-token-not-registered'
      ) {
        return {
          success: false,
          message: 'Token is no longer valid',
        };
      }

      return {
        success: false,
        message: 'Failed to send push notification',
        error: { message: sanitizedErrorMsg },
      };
    }
  }

  public static async sendBulkNotifications(
    params: SendBulkNotificationsParams
  ): Promise<BulkNotificationResult> {
    const { tokens, payload, options = {} } = params;
    const results: NotificationResult[] = [];
    let totalSent = 0;
    let totalFailed = 0;

    // FCM supports sending to up to 500 tokens at once using sendMulticast
    // But we'll use individual sends for better error handling per token
    const batchSize = 10;
    for (let i = 0; i < tokens.length; i += batchSize) {
      const batch = tokens.slice(i, i + batchSize);

      const batchPromises = batch.map(token =>
        this.sendNotification({ token, payload, options })
      );

      const batchResults = await Promise.allSettled(batchPromises);

      batchResults.forEach(result => {
        if (result.status === 'fulfilled') {
          results.push(result.value);
          if (result.value.success) {
            totalSent++;
          } else {
            totalFailed++;
          }
        } else {
          results.push({
            success: false,
            message: 'Promise rejected',
            error: result.reason,
          });
          totalFailed++;
        }
      });
    }

    return {
      success: totalSent > 0,
      totalSent,
      totalFailed,
      results,
    };
  }

  public static async send(
    params: SendSimpleNotificationParams
  ): Promise<NotificationResult> {
    const { token, title, message } = params;
    return this.sendNotification({
      token,
      payload: { title, message },
    });
  }

  public static async sendWithOptions(
    params: SendWithOptionsParams
  ): Promise<NotificationResult> {
    const { token, title, message, customOptions = {} } = params;
    const payload: NotificationPayload = {
      title,
      message,
      ...customOptions,
    };

    return this.sendNotification({ token, payload });
  }

  public static validateToken(token: any): token is string {
    return typeof token === 'string' && token.length > 0;
  }

  public static async sendTestNotification(token: string): Promise<NotificationResult> {
    return this.send({
      token,
      title: 'Test Notification',
      message: 'This is a test push notification from Quick Connect!',
    });
  }
}

export const send = (
  params: SendSimpleNotificationParams
): Promise<NotificationResult> => PushNotificationUtils.send(params);
