package org.raddatz.familienarchiv.document.annotation;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.raddatz.familienarchiv.document.annotation.CreateAnnotationDTO;
import org.raddatz.familienarchiv.document.annotation.UpdateAnnotationDTO;
import org.raddatz.familienarchiv.user.AppUser;
import org.raddatz.familienarchiv.document.Document;
import org.raddatz.familienarchiv.document.annotation.DocumentAnnotation;
import org.raddatz.familienarchiv.security.Permission;
import org.raddatz.familienarchiv.security.RequirePermission;
import org.raddatz.familienarchiv.document.annotation.AnnotationService;
import org.raddatz.familienarchiv.document.DocumentService;
import org.raddatz.familienarchiv.user.UserService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/documents/{documentId}/annotations")
@RequiredArgsConstructor
@Slf4j
public class AnnotationController {

    private final AnnotationService annotationService;
    private final DocumentService documentService;
    private final UserService userService;

    @GetMapping
    public List<DocumentAnnotation> listAnnotations(@PathVariable UUID documentId) {
        return annotationService.listAnnotations(documentId);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @RequirePermission({Permission.ANNOTATE_ALL, Permission.WRITE_ALL})
    public DocumentAnnotation createAnnotation(
            @PathVariable UUID documentId,
            @RequestBody CreateAnnotationDTO dto,
            Authentication authentication) {
        UUID userId = resolveUserId(authentication);
        Document doc = documentService.getDocumentById(documentId);
        return annotationService.createAnnotation(documentId, dto, userId, doc.getFileHash());
    }

    @PatchMapping("/{annotationId}")
    @RequirePermission({Permission.ANNOTATE_ALL, Permission.WRITE_ALL})
    public DocumentAnnotation updateAnnotation(
            @PathVariable UUID documentId,
            @PathVariable UUID annotationId,
            @Valid @RequestBody UpdateAnnotationDTO dto) {
        return annotationService.updateAnnotation(documentId, annotationId, dto);
    }

    @DeleteMapping("/{annotationId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @RequirePermission({Permission.ANNOTATE_ALL, Permission.WRITE_ALL})
    public void deleteAnnotation(
            @PathVariable UUID documentId,
            @PathVariable UUID annotationId,
            Authentication authentication) {
        UUID userId = resolveUserId(authentication);
        annotationService.deleteAnnotation(documentId, annotationId, userId);
    }

    // ─── private helpers ──────────────────────────────────────────────────────

    private UUID resolveUserId(Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) return null;
        try {
            AppUser user = userService.findByEmail(authentication.getName());
            return user != null ? user.getId() : null;
        } catch (Exception e) {
            log.warn("Could not resolve user for annotation: {}", e.getMessage());
            return null;
        }
    }
}
