package de.cannamanage.api.controller;

import de.cannamanage.domain.entity.TenantContext;
import de.cannamanage.domain.entity.User;
import de.cannamanage.service.DsgvoService;
import de.cannamanage.service.repository.UserRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.Map;
import java.util.UUID;

import static org.springframework.http.HttpStatus.NOT_FOUND;

@RestController
@RequestMapping("/api/v1/dsgvo")
@RequiredArgsConstructor
@Tag(name = "DSGVO", description = "Data export and deletion (GDPR Art. 15 & 17)")
public class DsgvoController {

    private final DsgvoService dsgvoService;
    private final UserRepository userRepository;

    /**
     * Art. 15 DSGVO — Export all personal data as JSON.
     */
    @GetMapping("/export")
    @Operation(summary = "Export all personal data (Art. 15 DSGVO)")
    public ResponseEntity<Map<String, Object>> exportData(Authentication auth) {
        UUID userId = resolveUserId(auth);
        UUID tenantId = TenantContext.getCurrentTenant();
        Map<String, Object> data = dsgvoService.exportUserData(userId, tenantId);
        return ResponseEntity.ok(data);
    }

    /**
     * Art. 17 DSGVO — Right to erasure.
     * Anonymizes personal data, deactivates account.
     */
    @DeleteMapping("/delete")
    @Operation(summary = "Delete account and anonymize data (Art. 17 DSGVO)")
    public ResponseEntity<Map<String, String>> deleteAccount(Authentication auth) {
        UUID userId = resolveUserId(auth);
        dsgvoService.deleteUserData(userId);
        return ResponseEntity.ok(Map.of(
                "status", "deleted",
                "message", "Dein Konto wurde gelöscht und deine Daten anonymisiert."
        ));
    }

    private UUID resolveUserId(Authentication auth) {
        // JwtAuthFilter sets the Authentication principal to the userId (the JWT subject),
        // so auth.getName() is the userId UUID — NOT an email. Parse it directly.
        UUID userId;
        try {
            userId = UUID.fromString(auth.getName());
        } catch (IllegalArgumentException e) {
            throw new ResponseStatusException(NOT_FOUND, "User not found");
        }
        if (!userRepository.existsById(userId)) {
            throw new ResponseStatusException(NOT_FOUND, "User not found");
        }
        return userId;
    }
}
