package de.oaa.libredeck.web.controller;

import de.oaa.libredeck.web.model.PlaylistSummary;
import de.oaa.libredeck.web.service.applemusic.AppleMusicApiClient;
import de.oaa.libredeck.web.service.applemusic.AppleMusicAuthRequiredException;
import de.oaa.libredeck.web.service.applemusic.AppleMusicTokenGenerator;
import de.oaa.libredeck.web.service.applemusic.AppleMusicTokenStore;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/apple")
@RequiredArgsConstructor
public class AppleMusicController {

    private final AppleMusicTokenStore     tokenStore;
    private final AppleMusicApiClient      apiClient;
    private final AppleMusicTokenGenerator tokenGen;

    @GetMapping("/configured")
    public Map<String, Boolean> configured() {
        return Map.of("configured", tokenGen.isConfigured());
    }

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

    /** Returns the developer JWT for MusicKit JS initialisation (public – JWT is designed to be shared). */
    @GetMapping("/developer-token")
    public ResponseEntity<?> developerToken() {
        if (!tokenGen.isConfigured()) {
            return ResponseEntity.status(503).body(Map.of("error", "not_configured"));
        }
        try {
            return ResponseEntity.ok(Map.of("token", tokenGen.getDeveloperToken()));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("error", e.getMessage()));
        }
    }

    /** Receives the Music User Token obtained by MusicKit JS in the browser and stores it in the session. */
    @PostMapping("/token")
    public Map<String, String> setToken(@RequestBody Map<String, String> body) {
        String token = body.getOrDefault("musicUserToken", "");
        if (!token.isBlank()) tokenStore.setMusicUserToken(token);
        return Map.of("status", "ok");
    }

    @PostMapping("/disconnect")
    public Map<String, String> disconnect() {
        tokenStore.setMusicUserToken(null);
        return Map.of("status", "ok");
    }

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