/**
 * Hook pour vérifier les permissions sur une playlist
 * T0485: Create Playlist Permission Frontend Checks
 */

import { useMemo } from 'react';
import { useAuthStore } from '@/stores/auth';
import { useCollaborators } from './usePlaylist';
import {
  canEdit,
  canDelete,
  canAddTracks,
  canRemoveTracks,
  canManageCollaborators,
  canRead,
} from '../utils/permissions';
import type { Playlist } from '../types';

/**
 * Hook pour obtenir les permissions d'un utilisateur sur une playlist
 * @param playlist La playlist à vérifier
 * @returns Un objet avec les permissions (canEdit, canDelete, canAddTracks, canRemoveTracks, canManageCollaborators, canRead)
 */
export function usePlaylistPermissions(playlist: Playlist | null | undefined) {
  const user = useAuthStore((state) => state.user);
  const userId = user?.id;

  // Récupérer les collaborateurs si la playlist existe
  const { data: collaborators } = useCollaborators(playlist?.id || 0);

  return useMemo(() => {
    if (!playlist) {
      return {
        canEdit: false,
        canDelete: false,
        canAddTracks: false,
        canRemoveTracks: false,
        canManageCollaborators: false,
        canRead: false,
        isOwner: false,
      };
    }

    return {
      canEdit: canEdit(playlist, userId, collaborators),
      canDelete: canDelete(playlist, userId),
      canAddTracks: canAddTracks(playlist, userId, collaborators),
      canRemoveTracks: canRemoveTracks(playlist, userId, collaborators),
      canManageCollaborators: canManageCollaborators(playlist, userId),
      canRead: canRead(playlist, userId, collaborators),
      isOwner: playlist.user_id === userId,
    };
  }, [playlist, userId, collaborators]);
}

