package de.cannamanage.api.controller;

import de.cannamanage.api.dto.notification.UpdatePreferencesRequest;
import de.cannamanage.domain.enums.NotificationChannel;
import de.cannamanage.service.NotificationPreferenceService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Notification preferences endpoints.
 * Any authenticated user can view/update their notification channel preferences.
 */
@RestController
@RequestMapping("/api/v1/notifications/preferences")
@RequiredArgsConstructor
public class NotificationPreferenceController {

    private final NotificationPreferenceService preferenceService;

    /**
     * Get user's notification channel preferences.
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getPreferences(@AuthenticationPrincipal UserDetails user) {
        UUID userId = UUID.fromString(user.getUsername());
        var prefs = preferenceService.getOrCreatePreferences(userId);

        var prefsMap = prefs.stream().collect(Collectors.toMap(
                p -> p.getChannel().name(),
                p -> (Object) p.isEnabled()
        ));

        return ResponseEntity.ok(Map.of("preferences", prefsMap));
    }

    /**
     * Update notification channel preferences.
     * IN_APP cannot be disabled (server-side enforcement).
     */
    @PutMapping
    public ResponseEntity<?> updatePreferences(
            @Valid @RequestBody UpdatePreferencesRequest request,
            @AuthenticationPrincipal UserDetails user) {

        UUID userId = UUID.fromString(user.getUsername());

        try {
            for (var entry : request.preferences().entrySet()) {
                preferenceService.updatePreference(userId, entry.getKey(), entry.getValue());
            }

            // Return updated preferences
            var prefs = preferenceService.getOrCreatePreferences(userId);
            var prefsMap = prefs.stream().collect(Collectors.toMap(
                    p -> p.getChannel().name(),
                    p -> (Object) p.isEnabled()
            ));

            return ResponseEntity.ok(Map.of("preferences", prefsMap));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
}
