'use client';

import { honeypot } from '@honeypot-run/core';

import { isProd, isStaging } from '@/utils/environment';
import { ActionName } from '@/utils/event-names';

import { EventSubscriber } from './';

const SUBSCRIBED_EVENTS = [
  // create
  ActionName.createSong,
  ActionName.uploadSong,
  ActionName.makePublic,
  ActionName.makePrivate,

  ActionName.downloadMP3,
  ActionName.downloadWAV,
  ActionName.downloadWAVUrlRetrieved,
  ActionName.downloadWAVTimeout,
  ActionName.downloadVideo,

  // listen
  ActionName.playSong,
  ActionName.playNewSong,
  ActionName.pauseSong,

  // social (song-level)
  ActionName.likeSong,
  ActionName.undoLikeSong,
  ActionName.dislikeSong,
  ActionName.undoDislikeSong,
  ActionName.shareSongWithLink,
  ActionName.shareSongWithX,
  ActionName.shareSongWithFacebook,
  ActionName.shareSongWithEmail,
  ActionName.shareSongWithLinkedIn,
  ActionName.shareSongWithReddit,

  // social (playlist-level)
  ActionName.likePlaylist,
  ActionName.undoLikePlaylist,
  ActionName.dislikePlaylist,
  ActionName.undoDislikePlaylist,
  ActionName.sharePlaylistWithLink,

  // social (artist-level)
  ActionName.followArtist,
  ActionName.unfollowArtist,

  // other
  ActionName.identify,
  ActionName.reportInappropriate,

  // FUTURE: trash events
] as const;

export const initHoneypot = async () => {
  if (typeof window !== 'undefined') {
    // Note: these are internal Cloudflare Workers
    const url = isProd
      ? 'https://suno.com/suno-prod-s8wir/js'
      : isStaging
        ? 'https://suno.com/suno-staging-cc1-e/js'
        : 'https://suno.com/suno-dev-bvjn8/js';
    honeypot.setup({ url });
    await honeypot.get();
  }
};

const pathSkipsHoneypot = (path: string) => {
  return (
    path.startsWith('/studio') ||
    path.startsWith('/edit') ||
    path.startsWith('/edit-legacy')
  );
};

export const honeypotSubscriber: EventSubscriber = {
  name: 'Honeypot',
  version: '0.1.0',
  description: 'Behavioral analytics and abusive behavior detection',
  push: async (event: string, properties?: Record<string, any>) => {
    // skip if we're outside of the window context
    if (typeof window === 'undefined') {
      return;
    }
    if (window) {
      if (pathSkipsHoneypot(window.location.pathname)) {
        return;
      } else {
        await initHoneypot();
      }
    }
    const eventName = properties?.actionName;

    if (!SUBSCRIBED_EVENTS.includes(eventName)) {
      return;
    }

    // prefer clerk ID
    const userId = properties?.clerkId || properties?.userId;
    if (userId) {
      honeypot.identify(userId);
      if (properties?.actionName == ActionName.identify) {
        // No further processing
        return;
      }
    }
    // this will land in Snowflake
    await honeypot.track(eventName, properties);
  },
};

export default honeypotSubscriber;
