package f1.controller;

import f1.db.UserDao;
import f1.entity.CommentItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.security.Principal;

@RestController
@RequestMapping("/api/comments")
public class CommentController {

    @Autowired
    private UserDao userDao;

    @GetMapping
    public List<List<CommentItem>> getComments(@RequestParam(defaultValue = "10") int limit,
            @RequestParam(defaultValue = "0") int offset,
            @RequestParam(required = false) Integer pageSize) {
        List<CommentItem> allComments = userDao.getRootComments(limit, offset);
        List<List<CommentItem>> pages = new ArrayList<>();

        if (allComments.isEmpty()) {
            return pages;
        }

        int size = (pageSize == null || pageSize <= 0) ? allComments.size() : pageSize;

        for (int i = 0; i < allComments.size(); i += size) {
            int end = Math.min(allComments.size(), i + size);
            pages.add(allComments.subList(i, end));
        }

        return pages;
    }

    @PostMapping
    public boolean addRootComment(@RequestBody Map<String, Object> payload) {
        int userId = (int) payload.get("user_id");
        String content = (String) payload.get("content");
        return userDao.addComment(userId, null, null, content);
    }

    @GetMapping("/{id}/replies")
    public Map<String, Object> getChildComments(@PathVariable int id) {
        Map<String, Object> response = new HashMap<>();
        response.put("parent", userDao.getCommentById(id));
        response.put("replies", userDao.getChildComments(id));
        return response;
    }

    @PostMapping("/{id}/replies")
    public boolean addChildComment(@PathVariable int id, @RequestBody Map<String, Object> payload) {
        int userId = (int) payload.get("user_id");
        String content = (String) payload.get("content");
        Integer responseId = payload.containsKey("response_id") ? (Integer) payload.get("response_id") : null;

        if (responseId == null) {
            responseId = id;
        }

        return userDao.addComment(userId, responseId, id, content);
    }

    @DeleteMapping("/{id}")
    public boolean deleteComment(@PathVariable int id, Principal principal) {
        CommentItem comment = userDao.getCommentById(id);
        if (comment == null) {
            return false;
        }
        if (!comment.getUsername().equals(principal.getName())) {
            return false;
        }
        return userDao.deleteComment(id);
    }
}
