package online.wesal.wesal.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import online.wesal.wesal.dto.ApiResponse;
import online.wesal.wesal.dto.CommentCreateRequestDTO;
import online.wesal.wesal.dto.CommentResponseDTO;

import java.util.List;
import online.wesal.wesal.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/posts/comments")
@CrossOrigin(origins = "*")
@Tag(name = "Comments", description = "Comment management endpoints")
public class CommentController {
    
    @Autowired
    private CommentService commentService;
    
    @PostMapping(value = "/create", consumes = "application/json", produces = "application/json")
    @Operation(summary = "Create comment", description = "Create a new comment or reply to an existing comment with 3-level nesting")
    public ResponseEntity<ApiResponse<CommentResponseDTO>> createComment(
            @Valid @RequestBody CommentCreateRequestDTO request,
            BindingResult bindingResult,
            Authentication authentication) {
        
        if (bindingResult.hasErrors()) {
            String errorMessage = bindingResult.getFieldErrors().stream()
                .map(error -> {
                    String field = error.getField();
                    if ("postId".equals(field)) return "Valid post ID is required";
                    if ("body".equals(field)) return "Comment body is required and cannot exceed 1000 characters";
                    return error.getDefaultMessage();
                })
                .findFirst()
                .orElse("Invalid input");
            return ResponseEntity.badRequest().body(ApiResponse.error(errorMessage));
        }
        
        try {
            CommentResponseDTO response = commentService.createComment(
                request.getPostId(), 
                request.getBody(), 
                request.getReplyComment()
            );
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (RuntimeException e) {
            String message;
            if (e.getMessage().contains("Post not found")) {
                message = "Post not found";
            } else if (e.getMessage().contains("Parent comment not found")) {
                message = "Comment you're replying to not found";
            } else if (e.getMessage().contains("User not found") || e.getMessage().contains("creator not found")) {
                message = "Authentication error. Please log in again.";
            } else {
                message = "Something went wrong.. We're sorry but try again later";
            }
            return ResponseEntity.badRequest().body(ApiResponse.error(message));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error("Something went wrong.. We're sorry but try again later"));
        }
    }
    
    @GetMapping("/list")
    @Operation(summary = "Get comments for post", description = "Get all comments for a specific post in hierarchical structure with nested replies")
    public ResponseEntity<ApiResponse<List<CommentResponseDTO>>> getCommentsByPostId(
            @RequestParam Long postId,
            Authentication authentication) {
        
        try {
            if (postId == null || postId <= 0) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Valid post ID is required"));
            }
            
            List<CommentResponseDTO> response = commentService.getCommentsByPostId(postId);
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error("Something went wrong.. We're sorry but try again later"));
        }
    }
}