package de.oaa.libredeck.web.controller;

import de.oaa.libredeck.web.model.PlaylistSummary;
import de.oaa.libredeck.web.service.spotify.SpotifyApiClient;
import de.oaa.libredeck.web.service.spotify.SpotifyAuthRequiredException;
import de.oaa.libredeck.web.service.spotify.SpotifyTokenRefresher;
import de.oaa.libredeck.web.service.spotify.SpotifyTokenStore;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/spotify")
@RequiredArgsConstructor
public class SpotifyController {

    private final SpotifyTokenStore    tokenStore;
    private final SpotifyApiClient     apiClient;
    private final SpotifyTokenRefresher tokenRefresher;

    @GetMapping("/connected")
    public Map<String, Boolean> connected() {
        if (!tokenStore.hasValidToken()) tokenRefresher.tryRefresh();
        return Map.of("connected", tokenStore.hasValidToken());
    }

    @GetMapping("/playlists")
    public ResponseEntity<?> playlists() {
        if (!tokenStore.hasValidToken() && !tokenRefresher.tryRefresh()) {
            return ResponseEntity.status(401).body(Map.of("error", "not_authenticated"));
        }
        try {
            List<PlaylistSummary> list = apiClient.fetchUserPlaylists();
            return ResponseEntity.ok(list);
        } catch (SpotifyAuthRequiredException e) {
            return ResponseEntity.status(401).body(Map.of("error", "not_authenticated"));
        } catch (IOException e) {
            return ResponseEntity.status(502).body(Map.of("error", e.getMessage()));
        }
    }
}
