package de.avatic.lcc.controller.maps;

import com.azure.core.credential.AccessToken;
import com.azure.identity.DefaultAzureCredentialBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/maps")
public class AzureMapsController {

    @Value("${azure.maps.client.id}")
    private String mapsClientId;

    @Value("${azure.maps.subscription.key}")
    private String mapsSubscriptionKey;

    @GetMapping("/token")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<Map<String, Object>> getAzureMapsToken() {
        try {
            // Verwende die DefaultAzureCredential für die Authentifizierung
            var credential = new DefaultAzureCredentialBuilder().build();

            // Fordere ein Token für Azure Maps an
            AccessToken token = credential.getToken(
                    new com.azure.core.credential.TokenRequestContext()
                            .addScopes("https://atlas.microsoft.com/.default")
            ).block();

            Map<String, Object> response = new HashMap<>();
            response.put("token", token.getToken());
            response.put("expiresOn", token.getExpiresAt().toEpochSecond());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}