package handlers

import (
	"fmt"
	"net/http"

	"git.linuxforward.com/byop/byop-engine/dbstore"
	"git.linuxforward.com/byop/byop-engine/models"
	"git.linuxforward.com/byop/byop-engine/services"
	"github.com/gin-gonic/gin"
)

type PreviewHandler struct {
	previewService services.PreviewService
	store          *dbstore.SQLiteStore
}

func NewPreviewHandler(previewService services.PreviewService, store *dbstore.SQLiteStore) *PreviewHandler {
	return &PreviewHandler{
		previewService: previewService,
		store:          store,
	}
}

// CreatePreview handles the creation of a new preview session.
func (h *PreviewHandler) CreatePreview(c *gin.Context) {
	ctx := c.Request.Context()

	var requestBody struct {
		AppId uint `json:"app_id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&requestBody); err != nil {
		validationErrors := map[string]string{"request_body": fmt.Sprintf("Invalid request body: %v", err)}
		appErr := models.NewErrValidation("invalid_preview_request", validationErrors, err)
		models.RespondWithError(c, appErr)
		return
	}

	preview, err := h.previewService.CreatePreview(ctx, requestBody.AppId)
	if err != nil {
		models.RespondWithError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{"preview": preview})
}

// GetPreview retrieves details of a specific preview session.
func (h *PreviewHandler) GetPreview(c *gin.Context) {
	ctx := c.Request.Context()

	previewId, err := parseUintID(c, "preview_id")
	if err != nil {
		models.RespondWithError(c, err)
		return
	}

	preview, err := h.store.GetPreviewByID(ctx, previewId)
	if err != nil {
		models.RespondWithError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{"preview": preview})
}
