package handlers

import (
	"encoding/json"
	"net/http"
	"time"

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

func ListFiles(client valkey.Client) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		upload_id := r.PathValue("upload_id")
		if upload_id == "" {
			w.WriteHeader(http.StatusBadRequest)
			return
		}

		expiresInt, err := client.Do(r.Context(), client.B().Ttl().Key(upload_id).Build()).AsInt64()
		if err != nil {
			http.Error(w, err.Error(), http.StatusNotFound)
			return
		}
		expiresIn := time.Second * time.Duration(expiresInt)
		expires := time.Now().Add(expiresIn)

		files_json, err := client.Do(r.Context(),
			client.B().Get().Key(upload_id).Build()).ToString()
		if err != nil {
			http.Error(w, err.Error(), http.StatusNotFound)
			return
		}

		var fileIds []string

		err = json.Unmarshal([]byte(files_json), &fileIds)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		files := make([]pages.File, len(fileIds))
		for i, fileid := range fileIds {
			filename, err := client.Do(r.Context(), client.B().Get().Key(fileid+":filename").Build()).ToString()
			if err != nil {
				continue
			}
			files[i] = pages.File{
				Filename: filename,
				Key:      fileid,
			}
		}

		templ.Handler(pages.ListShareContents(expires, upload_id, files)).ServeHTTP(w, r)
	}
}
