import { apiClient } from '@/services/api/client';
import { Playlist, PaginatedResponse } from '@/types/api';
import { playlistSchema } from '@/schemas/apiSchemas';

/**
 * Service pour la gestion des playlists
 * Aligné avec /api/v1/playlists backend
 */
export const playlistService = {
  /**
   * Liste les playlists de l'utilisateur ou publiques
   */
  list: async (params?: {
    page?: number;
    limit?: number;
    user_id?: string;
    search?: string;
  }) => {
    const response = await apiClient.get<PaginatedResponse<Playlist>>(
      '/playlists',
      { params },
    );
    const data = response.data as any;
    const items = data.list || data.items || data.playlists || [];

    return {
      playlists: items,
      pagination: data.pagination || {
        total: data.total || items.length,
        page: data.page || params?.page || 1,
        limit: data.limit || params?.limit || 10,
        total_pages: data.total_pages || 1,
      },
    };
  },

  /**
   * Recherche des playlists
   */
  search: async (query: string) => {
    const response = await apiClient.get<Playlist[]>('/playlists/search', {
      params: { query },
    });
    return { playlists: response.data };
  },

  /**
   * Récupère une playlist par son ID
   */
  get: async (id: string) => {
    const response = await apiClient.get<Playlist>(`/playlists/${id}`, {
      validateSchema: playlistSchema,
    } as any);
    return { playlist: response.data };
  },

  /**
   * Crée une nouvelle playlist
   */
  create: async (data: {
    title: string;
    description?: string;
    is_public?: boolean;
  }) => {
    const response = await apiClient.post<Playlist>('/playlists', data, {
      validateSchema: playlistSchema,
    } as any);
    return response.data;
  },

  /**
   * Met à jour une playlist existante
   */
  update: async (id: string, data: Partial<Playlist>) => {
    const response = await apiClient.put<Playlist>(`/playlists/${id}`, data, {
      validateSchema: playlistSchema,
    } as any);
    return response.data;
  },

  /**
   * Supprime une playlist
   */
  delete: async (id: string) => {
    await apiClient.delete(`/playlists/${id}`);
  },

  /**
   * Ajoute un morceau à une playlist
   */
  addTrack: async (playlistId: string, trackId: string) => {
    const response = await apiClient.post<Playlist>(
      `/playlists/${playlistId}/tracks`,
      { track_id: trackId },
    );
    return response.data;
  },

  /**
   * Retire un morceau d'une playlist
   */
  removeTrack: async (playlistId: string, trackId: string) => {
    await apiClient.delete(`/playlists/${playlistId}/tracks/${trackId}`);
  },

  /**
   * Réordonne les morceaux d'une playlist
   */
  reorderTracks: async (playlistId: string, trackIds: string[]) => {
    const response = await apiClient.put<Playlist>(
      `/playlists/${playlistId}/tracks/reorder`,
      { track_ids: trackIds },
    );
    return response.data;
  },

  /**
   * Récupère des recommandations de playlists
   */
  getRecommendations: async () => {
    const response = await apiClient.get<Playlist[]>(
      '/playlists/recommendations',
    );
    return { playlists: response.data };
  },

  /**
   * Gestion des collaborateurs
   */
  addCollaborator: async (
    playlistId: string,
    userId: string,
    role: string = 'editor',
  ) => {
    return await apiClient.post(`/playlists/${playlistId}/collaborators`, {
      user_id: userId,
      role,
    });
  },

  getCollaborators: async (playlistId: string) => {
    return await apiClient.get(`/playlists/${playlistId}/collaborators`);
  },

  updateCollaborator: async (
    playlistId: string,
    userId: string,
    role: string,
  ) => {
    return await apiClient.put(
      `/playlists/${playlistId}/collaborators/${userId}`,
      { role },
    );
  },

  removeCollaborator: async (playlistId: string, userId: string) => {
    return await apiClient.delete(
      `/playlists/${playlistId}/collaborators/${userId}`,
    );
  },

  /**
   * Partage
   */
  createShareLink: async (playlistId: string) => {
    const response = await apiClient.post<{ share_url: string }>(
      `/playlists/${playlistId}/share`,
    );
    return response.data;
  },
};
