package de.oaa.libredeck.web.controller;

import de.oaa.libredeck.web.model.PlaylistSummary;
import de.oaa.libredeck.web.service.tidal.TidalApiClient;
import de.oaa.libredeck.web.service.tidal.TidalAuthRequiredException;
import de.oaa.libredeck.web.service.tidal.TidalTokenStore;
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("/tidal")
@RequiredArgsConstructor
public class TidalController {

    private final TidalTokenStore tokenStore;
    private final TidalApiClient  apiClient;

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

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