import { Track } from "./db";
import { api } from "./apiClient";

export interface StaticPlaylist {
    id: string;
    title: string;
    description: string;
    cover_url: string;
    tracks: Track[];
    type: 'Album' | 'Artist' | 'Playlist';
    creator?: string;
}

export const libraryService = {
    async getLibrary(): Promise<StaticPlaylist> {
        // Fetch "Liked Songs" or main library from backend
        // Assuming backend has an endpoint or we treat "Trending" as default
        return await api.get<StaticPlaylist>('/browse'); // Simplified fallback
    },

    async _generateMockContent(): Promise<void> {
        // No-op in API mode
    },

    async getBrowseContent(): Promise<Record<string, StaticPlaylist[]>> {
        return await api.get<Record<string, StaticPlaylist[]>>('/browse');
    },

    async getPlaylist(id: string): Promise<StaticPlaylist | null> {
        try {
            return await api.get<StaticPlaylist>(`/playlists/${id}`);
        } catch (e) {
            console.error("Failed to fetch playlist", id, e);
            return null;
        }
    },

    async getRecommendations(seedTrackId?: string): Promise<Track[]> {
        // Use trending as recommendations for now
        const data = await api.get<{ tracks: Track[] }>('/trending');
        return data.tracks || [];
    },

    async getRecommendedAlbums(seedArtist?: string): Promise<StaticPlaylist[]> {
        const data = await api.get<Record<string, any>>('/browse');
        // Flatten all albums from categories
        const albums: StaticPlaylist[] = [];
        Object.values(data).forEach((list: any) => {
            if (Array.isArray(list)) albums.push(...list);
        });
        return albums.slice(0, 8);
    },

    async search(query: string): Promise<Track[]> {
        try {
            // Encode query safely is handled by URLSearchParams in apiClient if passed as params, 
            // but here we are constructing url manually? api.get accepts params.
            const res = await api.get<{ tracks: Track[] }>('/search', { query }); // Backend expects 'query' param
            return res.tracks || [];
        } catch (e) {
            return [];
        }
    },

    // UTILITIES FOR DYNAMIC UPDATES
    updateTrackCover(trackId: string, newUrl: string) {
        console.log("Dynamic updates not implemented in Backend Mode");
    },

    updateAlbumCover(albumId: string, newUrl: string) {
        console.log("Dynamic updates not implemented in Backend Mode");
    }
};
