package de.oaa.libredeck.web.controller;

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

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import de.oaa.libredeck.web.model.Track;
import de.oaa.libredeck.web.service.pdf.PdfCardGenerator;
import de.oaa.libredeck.web.service.streaming.StreamingProvider;
import de.oaa.libredeck.web.service.streaming.StreamingProviderRegistry;
import lombok.RequiredArgsConstructor;

/**
 * Stateless REST API for the Android app.
 * No authentication required – uses the Deezer public API.
 */
@RestController
@RequestMapping("/api/v1")
@RequiredArgsConstructor
public class ApiController {

    private final StreamingProviderRegistry registry;
    private final PdfCardGenerator pdfGenerator;

    @GetMapping("/generate")
    public ResponseEntity<byte[]> generate(@RequestParam(name = "playlistUrl") String playlistUrl) throws IOException {
        StreamingProvider provider = registry.findForUrl(playlistUrl)
                .orElseThrow(() -> new IllegalArgumentException("Unsupported URL: " + playlistUrl));

        String playlistId    = provider.extractPlaylistId(playlistUrl);
        String playlistTitle = provider.fetchPlaylistTitle(playlistId);
        List<Track> tracks   = provider.fetchTracks(playlistId);
        byte[] pdf           = pdfGenerator.generate(playlistTitle, tracks);

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + sanitize(playlistTitle) + ".pdf\"")
                .body(pdf);
    }

    private String sanitize(String name) {
        return name.replaceAll("[^a-zA-Z0-9_\\-]", "_").toLowerCase();
    }

    // -------------------------------------------------------------------------
    // OAuth endpoints – commented out until Deezer re-enables app registration.
    // -------------------------------------------------------------------------
    // @GetMapping("/auth/{provider}/exchange")
    // public OAuthToken exchangeCode(@PathVariable String provider, @RequestParam String code) throws IOException {
    //     return registry.get(provider).exchangeCode(code);
    // }
    //
    // @GetMapping("/{provider}/playlists")
    // public List<PlaylistSummary> playlists(@PathVariable String provider,
    //                                        @RequestHeader(HttpHeaders.AUTHORIZATION) String auth) throws IOException {
    //     return registry.get(provider).fetchPlaylists(extractToken(auth));
    // }
    //
    // @GetMapping("/{provider}/generate")
    // public ResponseEntity<byte[]> generateWithAuth(@PathVariable String provider,
    //                                                @RequestParam String playlistId,
    //                                                @RequestParam String playlistTitle,
    //                                                @RequestHeader(HttpHeaders.AUTHORIZATION) String auth) throws IOException {
    //     String token       = extractToken(auth);
    //     List<Track> tracks = registry.get(provider).fetchTracks(token, playlistId);
    //     byte[] pdf         = pdfGenerator.generate(playlistTitle, tracks);
    //     return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF)
    //             .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + sanitize(playlistTitle) + ".pdf\"")
    //             .body(pdf);
    // }
    //
    // private String extractToken(String authHeader) {
    //     if (authHeader == null || !authHeader.startsWith("Bearer "))
    //         throw new IllegalArgumentException("Missing or invalid Authorization header");
    //     return authHeader.substring(7);
    // }
}
