package com.rjlresaka.servlet;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rjlresaka.dao.MessageDAO;
import com.rjlresaka.model.Message;
import com.rjlresaka.model.User;
import com.rjlresaka.util.FileStorageUtil;

@WebServlet("/app/files/download")
public class DownloadAttachmentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final MessageDAO messageDAO = new MessageDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        User authUser = (User) session.getAttribute("authUser");
        int messageId = parseInt(request.getParameter("id"));

        try {
            Message message = messageDAO.findAttachmentForDownload(messageId, authUser.getId(), getServletContext());
            if (message == null || !message.hasAttachment()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            Path filePath = FileStorageUtil.resolveStoredFile(message.getAttachmentPath(), getServletContext());
            if (!Files.exists(filePath)) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            response.setContentType(message.getAttachmentType() == null ? "application/octet-stream" : message.getAttachmentType());
            response.setHeader("Content-Disposition", "attachment; filename="" + message.getAttachmentName() + """);
            response.setContentLengthLong(Files.size(filePath));
            Files.copy(filePath, response.getOutputStream());
        } catch (Exception exception) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage());
        }
    }

    private int parseInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}
