package server

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"warpbox/lib/boxstore"
	"warpbox/lib/models"
)

func formatBrowserTime(value time.Time) string {
	if value.IsZero() {
		return ""
	}
	return value.UTC().Format(time.RFC3339)
}

func (app *App) handleIndex(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "index.html", gin.H{
		"RetentionOptions": app.retentionOptions(),
		"DefaultRetention": app.defaultRetentionOption().Key,
		"UploadsEnabled":   app.config.GuestUploadsEnabled && app.config.APIEnabled,
		"MaxFileSizeBytes": app.config.GlobalMaxFileSizeBytes,
		"MaxBoxSizeBytes":  app.config.GlobalMaxBoxSizeBytes,
	})
}

func (app *App) handleShowBox(ctx *gin.Context) {
	boxID := ctx.Param("id")
	if !boxstore.ValidBoxID(boxID) {
		ctx.String(http.StatusBadRequest, "Invalid box id")
		return
	}

	manifest, hasManifest, ok := app.authorizeBoxRequest(ctx, boxID, true)
	if !ok {
		return
	}

	files, err := boxstore.ListFiles(boxID)
	if err != nil {
		ctx.String(http.StatusNotFound, "Box not found")
		return
	}
	if hasManifest && manifest.OneTimeDownload {
		files = stripOneTimeThumbnailState(files)
	}

	downloadAll := "/box/" + boxID + "/download"
	if !app.config.ZipDownloadsEnabled || hasManifest && manifest.DisableZip {
		downloadAll = ""
	}

	ctx.HTML(http.StatusOK, "box.html", gin.H{
		"BoxID":          boxID,
		"Files":          files,
		"FileCount":      len(files),
		"DownloadAll":    downloadAll,
		"ZipOnly":        hasManifest && manifest.OneTimeDownload,
		"PollMS":         app.config.BoxPollIntervalMS,
		"RetentionLabel": manifest.RetentionLabel,
		"ExpiresAt":      manifest.ExpiresAt,
		"ExpiresAtISO":   formatBrowserTime(manifest.ExpiresAt),
	})
}
func (app *App) handleBoxStatus(ctx *gin.Context) {
	if !app.requireAPI(ctx) {
		return
	}

	boxID := ctx.Param("id")
	if !boxstore.ValidBoxID(boxID) {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid box id"})
		return
	}

	manifest, hasManifest, ok := app.authorizeBoxRequest(ctx, boxID, false)
	if !ok {
		return
	}

	var files []models.BoxFile
	if hasManifest && manifestFilesReady(manifest.Files) {
		files = boxstore.DecorateFiles(boxID, manifest.Files)
	} else {
		var err error
		files, err = boxstore.ListFiles(boxID)
		if err != nil {
			ctx.JSON(http.StatusNotFound, gin.H{"error": "Box not found"})
			return
		}
	}
	if hasManifest && manifest.OneTimeDownload {
		files = stripOneTimeThumbnailState(files)
	}

	ctx.JSON(http.StatusOK, gin.H{"box_id": boxID, "expires_at": formatBrowserTime(manifest.ExpiresAt), "files": files})
}
