package handlers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"git.hafen.run/lukas/timeshare/pages"
	"github.com/a-h/templ"
	"github.com/google/uuid"
	"github.com/valkey-io/valkey-go"
)

func UploadFiles(client valkey.Client) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		err := r.ParseMultipartForm(125_000_000) // 1G max memory usage
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		form := r.MultipartForm
		expiry_values := form.Value["expiry"]
		expiry, err := time.ParseDuration(expiry_values[0])
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		form_files := form.File["files"]
		files := make([]string, len(form_files))
		for i := range form_files {
			fid := uuid.New().String()
			files[i] = fid
			f, err := form_files[i].Open()
			if err != nil {
				continue
			}
			buf := new(bytes.Buffer)
			_, err = io.Copy(buf, f)
			if err != nil {
				continue
			}
			err = client.Do(r.Context(), client.B().Set().Key(fid+":filename").Value(form_files[i].Filename).Ex(expiry).Build()).Error()
			if err != nil {
				continue
			}

			err = client.Do(r.Context(), client.B().Set().Key(fid+":contents").Value(valkey.BinaryString(buf.Bytes())).Ex(expiry).Build()).Error()
			if err != nil {
				continue
			}
		}

		uid := uuid.New()
		files_b, _ := json.Marshal(files)
		err = client.Do(r.Context(), client.B().Set().Key(uid.String()).Value(string(files_b)).Ex(expiry).Build()).Error()

		templ.Handler(pages.Upload([]pages.Expiry{
			{DurationCode: "24h", DurationName: "24 Hours"},
			{DurationCode: "36h", DurationName: "36 Hours"},
			{DurationCode: "48h", DurationName: "48 Hours"},
			{DurationCode: "168h", DurationName: "1 Week"},
		}, fmt.Sprintf("https://share.lukaswerner.com/%s", uid.String()))).ServeHTTP(w, r)
	}
}
