package de.frigosped.dc.resource;

import de.frigosped.dc.model.ExportRequest;
import de.frigosped.dc.service.MarkdownExportService;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;

@Path("/export")
public class ExportResource {

    private static final Logger LOG = Logger.getLogger(ExportResource.class);

    @Inject
    MarkdownExportService exportService;

    /**
     * POST /export/markdown
     * Body: { "content": "...", "format": "DOCX" | "PDF" }
     * Returns the binary file with appropriate Content-Type.
     */
    @POST
    @Path("/markdown")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response convert(ExportRequest req) {
        if (req == null || req.getContent() == null || req.getContent().isBlank()) {
            return Response.status(Response.Status.BAD_REQUEST)
                           .entity("content must not be empty").build();
        }
        String format = req.getFormat() == null ? "PDF" : req.getFormat().toUpperCase();

        try {
            if ("DOCX".equals(format)) {
                byte[] bytes = exportService.toDocx(req.getContent());
                return Response.ok(bytes)
                    .header("Content-Type",
                        "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                    .header("Content-Disposition", "attachment; filename=\"report.docx\"")
                    .build();

            } else if ("PDF".equals(format)) {
                byte[] bytes = exportService.toPdf(req.getContent());
                return Response.ok(bytes)
                    .header("Content-Type", "application/pdf")
                    .header("Content-Disposition", "attachment; filename=\"report.pdf\"")
                    .build();

            } else {
                return Response.status(Response.Status.BAD_REQUEST)
                               .entity("format must be DOCX or PDF").build();
            }
        } catch (Exception e) {
            LOG.errorf(e, "Export fehlgeschlagen (format=%s)", format);
            return Response.serverError().entity("Export failed: " + e.getMessage()).build();
        }
    }
}
