package httpapi

import (
	"io"
	"net/http"
)

const maxScreenshotSize = 3 << 20 // 3 MB

func handlePlayerScreenshot(store *ScreenshotStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		r.Body = http.MaxBytesReader(w, r.Body, maxScreenshotSize)
		if err := r.ParseMultipartForm(maxScreenshotSize); err != nil {
			http.Error(w, "bad multipart form", http.StatusBadRequest)
			return
		}

		screenID := r.FormValue("screen_id")
		if screenID == "" {
			http.Error(w, "screen_id required", http.StatusBadRequest)
			return
		}

		file, header, err := r.FormFile("screenshot")
		if err != nil {
			http.Error(w, "screenshot file required", http.StatusBadRequest)
			return
		}
		defer file.Close()

		data, err := io.ReadAll(file)
		if err != nil {
			http.Error(w, "read error", http.StatusInternalServerError)
			return
		}

		mimeType := header.Header.Get("Content-Type")
		if mimeType == "" {
			mimeType = "image/png"
		}

		store.Save(screenID, data, mimeType)
		w.WriteHeader(http.StatusOK)
	}
}

func handleGetScreenshot(store *ScreenshotStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		screenID := r.PathValue("screenId")
		data, mimeType, ok := store.Get(screenID)
		if !ok {
			http.NotFound(w, r)
			return
		}
		w.Header().Set("Content-Type", mimeType)
		w.Header().Set("Cache-Control", "no-store")
		w.Write(data) //nolint:errcheck
	}
}
