import { Playlist } from '@/state/clipStore';
import { ClipsStore } from '@/state/clipStore';
import { SessionStore } from '@/state/sessionStore';

export const filterPlaylistToUserOwnedSongs = async (
  playlist: Playlist,
  clips: ClipsStore,
  session: SessionStore
): Promise<Playlist | null> => {
  if (playlist.playlist_clips && playlist.playlist_clips.length > 0) {
    const userOwnedSongs = playlist.playlist_clips
      .filter((playlistClip) => {
        const clip = playlistClip.clip;
        return clip && clip.user_id === session.userId;
      })
      .slice(0, 4);

    if (userOwnedSongs.length > 0) {
      return {
        ...playlist,
        playlist_clips: userOwnedSongs,
        num_total_results: userOwnedSongs.length,
      };
    }
  }

  await clips.loadPlaylist(playlist.id, 1);
  const updatedPlaylist = clips.playlistById[playlist.id];

  if (!updatedPlaylist) {
    return null;
  }

  const userOwnedSongs =
    updatedPlaylist.playlist_clips
      ?.filter((playlistClip) => {
        const clip = playlistClip.clip;
        return clip && clip.user_id === session.userId;
      })
      .slice(0, 4) || [];

  if (userOwnedSongs.length === 0) {
    return null;
  }

  return {
    ...updatedPlaylist,
    playlist_clips: userOwnedSongs,
    num_total_results: userOwnedSongs.length,
  };
};

/**
 * List of playlist IDs that are system-generated virtual playlists.
 * These playlists are read-only and cannot be edited by users.
 *
 * These IDs match the backend constants defined in:
 * studio_api/bots/playlist/api.py lines 128-137
 */
export const READONLY_PLAYLIST_IDS = [
  'liked',
  'on-repeat',
  'sharelist',
  'top_shorts',
  'new_songs_for_you',
  'following_listen',
  'engaged_user_top_songs',
  'suggested_creator_top_songs',
  'trending_creator_top_songs',
  'my_sharelist',
] as readonly string[];

/**
 * Determines if a user can edit a playlist (add, remove, reorder songs, or modify metadata).
 *
 * A user can edit a playlist if:
 * - The playlist is owned by the user (is_owned === true)
 * - AND the playlist is not a read-only system playlist
 *
 * @param playlist - The playlist object with ownership information
 * @returns true if the user can edit the playlist, false otherwise
 */
export function canUserEditPlaylist(playlist: Playlist): boolean {
  const isReadOnlyPlaylist = READONLY_PLAYLIST_IDS.includes(playlist.id);
  return playlist.is_owned === true && !isReadOnlyPlaylist;
}
