import { getToken } from 'firebase/messaging';
import { RECRUITMENT_URL, FB_VAPID_KEY } from '../../common/envVariables';
import { initializeMessaging, getMessagingInstance } from '../../config/firebase';
import { saveFcmToken } from '../../services/notification.service';
import { NOTIFICATION_TYPE } from './notificationConstant';

export const requestNotificationPermission = async () => {
  const permission = await Notification.requestPermission();
  if (permission !== 'granted') {
    return;
  }

  try {
    // Initialize messaging if not already initialized
    const messagingInstance = await initializeMessaging();
    if (!messagingInstance) {
      console.log('Firebase messaging is not supported in this browser');
      return;
    }
    
    const currentToken = await getToken(messagingInstance, {
      vapidKey: FB_VAPID_KEY,
    });
    
    if (currentToken) {
      await saveFcmToken({
        token: currentToken,
      });
    }
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error('An error occurred while retrieving token. ', err);
  }
};

export const redirectByNotificationType = (
  notificationType,
  id,
  inAppNotification = false
) => {
  if (!notificationType || !id) {
    // eslint-disable-next-line no-console
    console.error('Please provide both notification-type and id');
    return `${RECRUITMENT_URL}`;
  }

  const companyDetailRoute = `companies/${id}`;
  const planPageRoute = `choose-plan`;
  const jobDetailRoute = `jobs/${id}`;

  const redirectMap = {
    [NOTIFICATION_TYPE.NEW_COMPANY_REQUEST]: `${companyDetailRoute}`,
    [NOTIFICATION_TYPE.DOCUMENT_REUPLOADED]: `${companyDetailRoute}`,
    [NOTIFICATION_TYPE.ONLINE_PAYMENT_NOTIFICATION]: `${companyDetailRoute}`,
    [NOTIFICATION_TYPE.JC_PLAN_IS_GOING_TO_GET_EXPIRED]: `${planPageRoute}`,
    [NOTIFICATION_TYPE.JC_PARTICULAR_JOB_HAS_BEEN_IN_DRAFT]: `${jobDetailRoute}`,
    [NOTIFICATION_TYPE.PLAN_IS_GOING_TO_GET_EXPIRED]: `${planPageRoute}`,
    [NOTIFICATION_TYPE.PARTICULAR_JOB_HAS_BEEN_IN_DRAFT]: `${jobDetailRoute}`,
    [NOTIFICATION_TYPE.JOB_CREATED]: `${jobDetailRoute}`,
    [NOTIFICATION_TYPE.JOB_EXPIRY_DATE_CHANGED]: `${jobDetailRoute}`,
    [NOTIFICATION_TYPE.JOB_CLOSED]: `${jobDetailRoute}`,
  };

  let route = `${redirectMap[notificationType]}`;
  if (!inAppNotification) {
    route = RECRUITMENT_URL + route;
  }
  return route;
};
