package org.raddatz.familienarchiv.document.comment;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.raddatz.familienarchiv.document.comment.CreateCommentDTO;
import org.raddatz.familienarchiv.user.AppUser;
import org.raddatz.familienarchiv.document.comment.DocumentComment;
import org.raddatz.familienarchiv.security.Permission;
import org.raddatz.familienarchiv.security.RequirePermission;
import org.raddatz.familienarchiv.document.comment.CommentService;
import org.raddatz.familienarchiv.user.UserService;
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
@RequiredArgsConstructor
@Slf4j
public class CommentController {

    private final CommentService commentService;
    private final UserService userService;

    // ─── Block (transcription) comments ────────────────────────────────────────

    @GetMapping("/api/documents/{documentId}/transcription-blocks/{blockId}/comments")
    public List<DocumentComment> getBlockComments(
            @PathVariable UUID documentId,
            @PathVariable UUID blockId) {
        return commentService.getCommentsForBlock(blockId);
    }

    @PostMapping("/api/documents/{documentId}/transcription-blocks/{blockId}/comments")
    @ResponseStatus(HttpStatus.CREATED)
    @RequirePermission({Permission.ANNOTATE_ALL, Permission.WRITE_ALL})
    public DocumentComment postBlockComment(
            @PathVariable UUID documentId,
            @PathVariable UUID blockId,
            @RequestBody CreateCommentDTO dto,
            Authentication authentication) {
        AppUser author = resolveUser(authentication);
        return commentService.postBlockComment(documentId, blockId, dto.getContent(), dto.getMentionedUserIds(), author);
    }

    @PostMapping("/api/documents/{documentId}/transcription-blocks/{blockId}/comments/{commentId}/replies")
    @ResponseStatus(HttpStatus.CREATED)
    @RequirePermission({Permission.ANNOTATE_ALL, Permission.WRITE_ALL})
    public DocumentComment replyToBlockComment(
            @PathVariable UUID documentId,
            @PathVariable UUID blockId,
            @PathVariable UUID commentId,
            @RequestBody CreateCommentDTO dto,
            Authentication authentication) {
        AppUser author = resolveUser(authentication);
        return commentService.replyToComment(documentId, commentId, dto.getContent(), dto.getMentionedUserIds(), author);
    }

    // ─── Edit and delete (shared) ─────────────────────────────────────────────

    @PatchMapping("/api/documents/{documentId}/comments/{commentId}")
    @RequirePermission({Permission.ANNOTATE_ALL, Permission.WRITE_ALL})
    public DocumentComment editComment(
            @PathVariable UUID documentId,
            @PathVariable UUID commentId,
            @RequestBody CreateCommentDTO dto,
            Authentication authentication) {
        AppUser currentUser = resolveUser(authentication);
        return commentService.editComment(documentId, commentId, dto.getContent(), currentUser);
    }

    @DeleteMapping("/api/documents/{documentId}/comments/{commentId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteComment(
            @PathVariable UUID documentId,
            @PathVariable UUID commentId,
            Authentication authentication) {
        AppUser currentUser = resolveUser(authentication);
        commentService.deleteComment(documentId, commentId, currentUser);
    }

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

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