/**
 * @license
 * Copyright (c) The Authors (see the AUTHORS file)
 *
 * This source code is licensed under the GNU Affero General Public License v3.0 (AGPLv3).
 * You may obtain a copy of the AGPL v3.0 at https://www.gnu.org/licenses/agpl-3.0.html.
 */
package registryservice

import (
	"log/slog"
	"net/http"

	"github.com/1backend/1backend/sdk/go/datastore"
	"github.com/1backend/1backend/sdk/go/endpoint"
	"github.com/1backend/1backend/sdk/go/logger"
	registry "github.com/1backend/1backend/server/internal/services/registry/types"
	"github.com/gorilla/mux"
)

// @ID removeInstance
// @Summary Remove Instance
// @Description Removes a registered instance by ID.
// @Tags Registry Svc
// @Accept json
// @Produce json
// @Param id path string true "Instance ID"
// @Success 204 "No Content"
// @Failure 400 {object} registry.ErrorResponse "Invalid ID"
// @Failure 401 {object} registry.ErrorResponse "Unauthorized"
// @Failure 404 {object} registry.ErrorResponse "Service Not Found"
// @Failure 500 {object} registry.ErrorResponse "Internal Server Error"
// @Security BearerAuth
// @Router /registry-svc/instance/{id} [delete]
func (rs *RegistryService) RemoveInstance(
	w http.ResponseWriter,
	r *http.Request,
) {

	isAuthRsp, statusCode, err := rs.options.PermissionChecker.HasPermission(
		r,
		registry.PermissionInstanceDelete,
	)
	if err != nil {
		endpoint.WriteErr(w, statusCode, err)
		return
	}
	if !isAuthRsp.Authorized {
		endpoint.Unauthorized(w)
		return
	}

	vars := mux.Vars(r)
	instanceID := vars["id"]
	if instanceID == "" {
		endpoint.WriteString(w, http.StatusBadRequest, "Invalid ID")
		return
	}

	err = rs.removeInstanceByID(instanceID)
	if err != nil {
		if err == registry.ErrNotFound {
			endpoint.WriteString(w, http.StatusNotFound, "Service Not Found")
		} else {
			logger.Error(
				"Error removing instance",
				slog.Any("error", err),
			)
			endpoint.InternalServerError(w)
		}
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

func (rs *RegistryService) removeInstanceByID(id string) error {
	return rs.instanceStore.Query(datastore.Id(id)).Delete()
}
