package site

import (
	"net/http"

	"github.com/gocql/gocql"
	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/config/constants"
	siteservice "codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/service/site"
	siteusecase "codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/usecase/site"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/httperror"
	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/httpresponse"
)

// DeleteHandler handles site deletion HTTP requests
type DeleteHandler struct {
	service siteservice.DeleteSiteService
	logger  *zap.Logger
}

// ProvideDeleteHandler creates a new DeleteHandler
func ProvideDeleteHandler(service siteservice.DeleteSiteService, logger *zap.Logger) *DeleteHandler {
	return &DeleteHandler{
		service: service,
		logger:  logger,
	}
}

// Handle handles the HTTP request for deleting a site
// Requires JWT authentication and tenant context
func (h *DeleteHandler) Handle(w http.ResponseWriter, r *http.Request) {
	// Get tenant ID from context
	tenantIDStr, ok := r.Context().Value(constants.ContextKeyTenantID).(string)
	if !ok {
		h.logger.Error("tenant ID not found in context")
		httperror.ProblemUnauthorized(w, "Tenant context is required to access this resource.")
		return
	}

	tenantID, err := gocql.ParseUUID(tenantIDStr)
	if err != nil {
		h.logger.Error("invalid tenant ID format", zap.Error(err))
		httperror.ProblemBadRequest(w, "Invalid tenant ID format. Please ensure you have a valid session.")
		return
	}

	// Get site ID from path parameter
	siteIDStr := r.PathValue("id")
	if siteIDStr == "" {
		httperror.ProblemBadRequest(w, "Site ID is required in the request path.")
		return
	}

	// Validate UUID format
	if _, err := gocql.ParseUUID(siteIDStr); err != nil {
		httperror.ProblemBadRequest(w, "Invalid site ID format. Please provide a valid site ID.")
		return
	}

	// Call service
	input := &siteusecase.DeleteSiteInput{SiteID: siteIDStr}
	_, err = h.service.DeleteSite(r.Context(), tenantID, input)
	if err != nil {
		h.logger.Error("failed to delete site",
			zap.Error(err),
			zap.String("site_id", siteIDStr),
			zap.String("tenant_id", tenantID.String()))
		httperror.ProblemNotFound(w, "The requested site could not be found. It may have been deleted or you may not have access to it.")
		return
	}

	h.logger.Info("site deleted successfully",
		zap.String("site_id", siteIDStr),
		zap.String("tenant_id", tenantID.String()))

	// Write response
	httpresponse.OK(w, map[string]string{
		"message": "site deleted successfully",
		"site_id": siteIDStr,
	})
}
