package api

import (
	"fmt"
	"net/http"

	"github.com/AlchemyTelcoSolutions/callisto-so-bff/internal/domain/model"
	"github.com/AlchemyTelcoSolutions/utils/render"
	"github.com/google/uuid"
)

func (s *Server) respWithJson(w http.ResponseWriter, statusCode int, data interface{}) {
	w.WriteHeader(statusCode)
	w.Header().Set("Content-Type", "application/json")
	render.JSON(w, data)
}

func (s *Server) respFromProxy(w http.ResponseWriter, statusCode int, data []byte) {
	w.WriteHeader(statusCode)
	w.Header().Set("Content-Type", "application/json")
	if _, err := w.Write(data); err != nil {
		s.logger.Error("error writing payload to response", err)
	}
}

func (s *Server) respWithFile(w http.ResponseWriter, file *model.File) {
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", file.MIMEType)

	contentDisposition := fmt.Sprintf("attachment; filename=%s.%s", uuid.New().String(), file.GetFileExtension())
	if file.Name != "" {
		contentDisposition = fmt.Sprintf("attachment; filename=%s.%s", file.Name, file.GetFileExtension())
	}

	w.Header().Set("Content-Disposition", contentDisposition)

	if _, err := w.Write(file.Content); err != nil {
		s.logger.Error("error writing file bytes to response", err)
	}
}
