package de.oaa.xxx.subscription;

import de.oaa.xxx.user.UserService;
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.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/subscription")
public class SubscriptionController {

    private final UserService userService;
    private final SubscriptionLimitService limitService;

    public SubscriptionController(UserService userService,
                                  SubscriptionLimitService limitService) {
        this.userService = userService;
        this.limitService = limitService;
    }

    @GetMapping("/me")
    public ResponseEntity<Map<String, Object>> getMySubscription(Principal principal) {
        UUID userId = userService.requireUser(principal).getUserId();

        Map<String, Object> result = new LinkedHashMap<>();
        limitService.getActiveSubscription(userId).ifPresentOrElse(sub -> {
            result.put("subscriptionType", sub.getSubscriptionType());
            result.put("subscribedAt",    sub.getSubscribedAt());
            result.put("validUntil",      sub.getValidUntil());
            result.put("cancellableFrom", sub.getCancellableFrom());
        }, () -> {
            result.put("subscriptionType", SubscriptionType.STANDARD);
            result.put("subscribedAt",    null);
            result.put("validUntil",      null);
            result.put("cancellableFrom", null);
        });

        result.put("limits", Map.of(
                "maxLockTemplates",  limitService.maxLockTemplates(userId),
                "maxTaskGroups",     limitService.maxTaskGroups(userId),
                "maxTasksPerGroup",  limitService.maxTasksPerGroup(userId),
                "maxToys",           limitService.maxToys(userId)
        ));

        return ResponseEntity.ok(result);
    }
}
