package de.oaa.libredeck.web.service.deezer;

import de.oaa.libredeck.web.model.Track;
import de.oaa.libredeck.web.service.streaming.StreamingProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@RequiredArgsConstructor
public class DeezerProvider implements StreamingProvider {

    // Matches e.g. https://www.deezer.com/playlist/1234  or  .../de/playlist/1234
    private static final Pattern PLAYLIST_URL = Pattern.compile(
            "deezer\\.com(?:/[a-z]{2})?/playlist/(\\d+)"
    );

    private final DeezerApiClient apiClient;

    @Override
    public String getId() {
        return "deezer";
    }

    @Override
    public String getDisplayName() {
        return "Deezer";
    }

    @Override
    public boolean supportsUrl(String url) {
        return url != null && PLAYLIST_URL.matcher(url).find();
    }

    @Override
    public String extractPlaylistId(String url) {
        Matcher m = PLAYLIST_URL.matcher(url);
        if (!m.find()) throw new IllegalArgumentException("Not a valid Deezer playlist URL: " + url);
        return m.group(1);
    }

    @Override
    public String fetchPlaylistTitle(String playlistId) throws IOException {
        return apiClient.fetchPlaylistTitle(playlistId);
    }

    @Override
    public List<Track> fetchTracks(String playlistId) throws IOException {
        return apiClient.fetchTracks(playlistId);
    }

    @Override
    public String fetchTrackYear(String trackId) {
        return apiClient.fetchTrackYear(trackId);
    }

    // -------------------------------------------------------------------------
    // OAuth methods – commented out until Deezer re-enables app registration.
    // Re-enable together with AuthController and DeezerConfig when an app-id
    // / app-secret is available.
    // -------------------------------------------------------------------------
    // @Override public String buildAuthorizationUrl(String state) {
    //     return "https://connect.deezer.com/oauth/auth.php"
    //             + "?app_id=" + config.getAppId()
    //             + "&redirect_uri=" + URLEncoder.encode(config.getRedirectUri(), UTF_8)
    //             + "&perms=basic_access,manage_library"
    //             + "&state=" + state;
    // }
    // @Override public OAuthToken exchangeCode(String code) throws IOException {
    //     return apiClient.exchangeCode(code, config);
    // }
    // @Override public List<PlaylistSummary> fetchPlaylists(String accessToken) throws IOException {
    //     return apiClient.fetchPlaylists(accessToken);
    // }
    // @Override public List<Track> fetchTracks(String accessToken, String playlistId) throws IOException {
    //     return apiClient.fetchTracks(playlistId); // token currently unused
    // }
}
