package com.codebyte.api.common.web;

import com.codebyte.api.common.error.ErrorCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;

/** Writes an RFC 7807 problem (with a stable {@code code}) directly to a servlet response. */
public final class ProblemDetailResponder {

    private ProblemDetailResponder() {}

    public static void write(
            HttpServletResponse response, ObjectMapper objectMapper, ErrorCode code)
            throws IOException {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(code.getStatus(), code.getTitle());
        problem.setTitle(code.getTitle());
        problem.setProperty("code", code.name());

        response.setStatus(code.getStatus().value());
        response.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE);
        objectMapper.writeValue(response.getWriter(), problem);
    }
}
