import api from './api';
import type { Track } from '../types';

export interface ListTracksParams {
  limit?: number;
  offset?: number;
  sort_by?: 'title' | 'artist' | 'album_id' | 'duration' | 'play_count';
  order?: 'ASC' | 'DESC';
  search?: string;
}

export const trackService = {
  // GET /api/tracks
  async listTracks(params?: ListTracksParams): Promise<Track[]> {
    const res = await api.get<Track[]>('/tracks', { params });
    return res.data;
  },

  // GET /api/tracks/seeds — a random playable sample and the size of the pool.
  async listSeedTracks(limit = 50): Promise<{ total: number; tracks: Track[] }> {
    const res = await api.get<{ total: number; tracks: Track[] }>('/tracks/seeds', { params: { limit } });
    return res.data;
  },

  // GET /api/tracks/:id
  async getTrack(id: string): Promise<Track> {
    const res = await api.get<Track>(`/tracks/${id}`);
    return res.data;
  },

  // Plain URL for an <audio> src. GET /api/tracks/:id/stream (supports Range).
  getStreamUrl(id: string): string {
    const base = api.defaults.baseURL ?? '/api';
    return `${base}/tracks/${id}/stream`;
  },

  // POST /api/tracks
  async createTrack(data: Partial<Track>): Promise<Track> {
    const res = await api.post<Track>('/tracks', data);
    return res.data;
  },

  // PUT /api/tracks/:id
  async updateTrack(id: string, data: Partial<Track>): Promise<Track> {
    const res = await api.put<Track>(`/tracks/${id}`, data);
    return res.data;
  },

  // DELETE /api/tracks/:id
  async deleteTrack(id: string): Promise<{ status: string }> {
    const res = await api.delete<{ status: string }>(`/tracks/${id}`);
    return res.data;
  },

  // GET /api/tracks/:id/lyrics
  async getLyrics(id: string): Promise<{ lyrics_text: string | null; synced_lyrics: unknown | null; provider: string | null }> {
    const res = await api.get(`/tracks/${id}/lyrics`);
    return res.data;
  },
};
