// import { Queue, Worker } from 'bullmq';
// import { db } from '@/src/db/db_index'
import { scaffoldAssetUrl } from '@/src/lib/s3-client'
import { queueDataPusher } from '@/src/lib/queue-data-pusher'
import {
  NOTIFS_QUEUE,
  ORDER_PLACED_MESSAGE,
  PAYMENT_FAILED_MESSAGE,
  ORDER_PACKAGED_MESSAGE,
  ORDER_OUT_FOR_DELIVERY_MESSAGE,
  ORDER_DELIVERED_MESSAGE,
  ORDER_CANCELLED_MESSAGE,
  REFUND_INITIATED_MESSAGE
} from '@/src/lib/const-strings';


export const notificationQueue:any = {};

// export const notificationQueue = new Queue(NOTIFS_QUEUE, {
//   connection: { url: redisUrl },
//   defaultJobOptions: {
//     removeOnComplete: true,
//     removeOnFail: 10,
//     attempts: 3,
//   },
// });

export const notificationWorker:any = {};
// export const notificationWorker = new Worker(NOTIFS_QUEUE, async (job) => {
//   if (!job) return;
//
//   const { name, data } = job;
//   console.log(`Processing notification job ${job.id} - ${name}`);
//
//   if (name === 'send-admin-notification') {
//     await sendAdminNotification(data);
//   } else if (name === 'send-notification') {
//     // Handle legacy notification type
//     console.log('Legacy notification job - not implemented yet');
//   }
// }, {
//   connection: { url: redisUrl },
//   concurrency: 5,
// });

export async function sendAdminNotification(data: {
  token: string;
  title: string;
  body: string;
  imageUrl: string | null;
}) {
  const { token, title, body, imageUrl } = data;
  const { Expo } = await import('expo-server-sdk')

  // Validate Expo push token
  if (!Expo.isExpoPushToken(token)) {
    console.error(`Invalid Expo push token: ${token}`);
    return;
  }
  
  // Generate signed URL for image if provided
  const signedImageUrl = imageUrl ? scaffoldAssetUrl(imageUrl) : null;
  
  // Send notification
  const expo = new Expo();
  const message = {
    to: token,
    sound: 'default',
    title,
    body,
    data: { imageUrl },
    ...(signedImageUrl ? {
      attachments: [
        {
          url: signedImageUrl,
          contentType: 'image/jpeg',
        }
      ]
    } : {}),
  };
  
  try {
    const [ticket] = await expo.sendPushNotificationsAsync([message]);
  } catch (error) {
    console.log(`Failed to send notification:`, error);
    throw error;
  }
}

// notificationWorker.on('completed', (job) => {
//   if (job) console.log(`Notification job ${job.id} completed`);
// });
// notificationWorker.on('failed', (job, err) => {
//   if (job) console.error(`Notification job ${job.id} failed:`, err);
// });

export async function scheduleNotification(userId: number, payload: any, options?: { delay?: number; priority?: number }) {
  const jobData = { userId, ...payload };
  await queueDataPusher.pushNotifQueue({ name: 'send-notification', jobData, options })
}

// Utility methods for specific notification events
export async function sendOrderPlacedNotification(userId: number, orderId?: string) {
  await scheduleNotification(userId, {
    title: 'Order Placed',
    body: ORDER_PLACED_MESSAGE,
    type: 'order',
    orderId
  });
}

export async function sendPaymentFailedNotification(userId: number, orderId?: string) {
  await scheduleNotification(userId, {
    title: 'Payment Failed',
    body: PAYMENT_FAILED_MESSAGE,
    type: 'payment',
    orderId
  });
}

export async function sendOrderPackagedNotification(userId: number, orderId?: string) {
  await scheduleNotification(userId, {
    title: 'Order Packaged',
    body: ORDER_PACKAGED_MESSAGE,
    type: 'order',
    orderId
  });
}

export async function sendOrderOutForDeliveryNotification(userId: number, orderId?: string) {
  await scheduleNotification(userId, {
    title: 'Out for Delivery',
    body: ORDER_OUT_FOR_DELIVERY_MESSAGE,
    type: 'order',
    orderId
  });
}

export async function sendOrderDeliveredNotification(userId: number, orderId?: string) {
  await scheduleNotification(userId, {
    title: 'Order Delivered',
    body: ORDER_DELIVERED_MESSAGE,
    type: 'order',
    orderId
  });
}

export async function sendOrderCancelledNotification(userId: number, orderId?: string) {
  await scheduleNotification(userId, {
    title: 'Order Cancelled',
    body: ORDER_CANCELLED_MESSAGE,
    type: 'order',
    orderId
  });
}

export async function sendRefundInitiatedNotification(userId: number, orderId?: string) {
  await scheduleNotification(userId, {
    title: 'Refund Initiated',
    body: REFUND_INITIATED_MESSAGE,
    type: 'refund',
    orderId
  });
}
//
// process.on('SIGTERM', async () => {
//   await notificationQueue.close();
//   await notificationWorker.close();
// });
