// monorepo/cloud/backend/internal/maplefile/interface/http/file/report_download_completed.go
package file

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

	"go.uber.org/zap"

	"github.com/gocql/gocql"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/interface/http/middleware"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/httperror"
)

type ReportDownloadCompletedHTTPHandler struct {
	config     *config.Configuration
	logger     *zap.Logger
	middleware middleware.Middleware
}

func NewReportDownloadCompletedHTTPHandler(
	config *config.Configuration,
	logger *zap.Logger,
	middleware middleware.Middleware,
) *ReportDownloadCompletedHTTPHandler {
	logger = logger.Named("ReportDownloadCompletedHTTPHandler")
	return &ReportDownloadCompletedHTTPHandler{
		config:     config,
		logger:     logger,
		middleware: middleware,
	}
}

func (*ReportDownloadCompletedHTTPHandler) Pattern() string {
	return "POST /api/v1/file/{id}/download-completed"
}

func (h *ReportDownloadCompletedHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Apply middleware before handling the request
	h.middleware.Attach(h.Execute)(w, req)
}

func (h *ReportDownloadCompletedHTTPHandler) Execute(w http.ResponseWriter, r *http.Request) {
	// Set response content type
	w.Header().Set("Content-Type", "application/json")

	// Extract file ID from the URL
	fileIDStr := r.PathValue("id")
	if fileIDStr == "" {
		httperror.RespondWithError(w, r, httperror.NewForBadRequestWithSingleField("file_id", "File ID is required"))
		return
	}

	// Validate UUID format
	_, err := gocql.ParseUUID(fileIDStr)
	if err != nil {
		h.logger.Error("invalid file ID format",
			zap.String("file_id", fileIDStr),
			zap.Error(err))
		httperror.RespondWithError(w, r, httperror.NewForBadRequestWithSingleField("file_id", "Invalid file ID format"))
		return
	}

	// Log the download completion (analytics/telemetry)
	h.logger.Debug("download completed reported",
		zap.String("file_id", fileIDStr))

	// Return success response
	response := map[string]interface{}{
		"success": true,
		"message": "Download completion recorded",
	}

	if err := json.NewEncoder(w).Encode(response); err != nil {
		h.logger.Error("failed to encode response",
			zap.String("file_id", fileIDStr),
			zap.Error(err))
		httperror.RespondWithError(w, r, err)
		return
	}
}
