package apihandler

import (
	"context"
	"net/http"

	"git.agecem.com/agecem/agecem-org/apiresponse"
	"github.com/labstack/echo/v4"
	"github.com/minio/minio-go/v7"
)

// V1BucketsGET affiche les buckets permis par server.documents.buckets, qui existent.
func (h *V1Handler) V1BucketsGET(c echo.Context) error {
	var response apiresponse.V1BucketsGET

	var buckets = make(map[string]string)

	for bucket_name, bucket_display_name := range h.Config.Server.Documents.Buckets {
		exists, err := h.MediaClient.MinioClient.BucketExists(context.Background(), bucket_name)
		if err != nil {
			response.StatusCode = http.StatusInternalServerError
			response.Message = "Error during minio#BucketExists"
			// response.Error = err.Error()

			return c.JSON(response.StatusCode, response)
		}

		if exists {
			buckets[bucket_name] = bucket_display_name
		}
	}

	response.StatusCode = http.StatusOK
	response.Message = "Buckets list successful"
	response.Data.Buckets = buckets

	return c.JSON(response.StatusCode, response)
}

func (h *V1Handler) V1BucketGET(c echo.Context) error {
	var response apiresponse.V1BucketGET

	bucket := c.Param("bucket")

	allowed := false
	for bucket_allowed := range h.Config.Server.Documents.Buckets {
		if bucket == bucket_allowed {
			allowed = true
		}
	}

	if !allowed {
		return c.JSON(apiresponse.NotFoundResponse())
	}

	ctx, cancel := context.WithCancel(context.Background())

	defer cancel()

	exists, err := h.MediaClient.MinioClient.BucketExists(ctx, bucket)
	if err != nil {
		response.StatusCode = http.StatusInternalServerError
		response.Message = "Error during minio#BucketExists"
		response.Error = err.Error()

		return c.JSON(response.StatusCode, response)
	}

	if !exists {
		return c.JSON(apiresponse.NotFoundResponse())
	}

	objectCh := h.MediaClient.MinioClient.ListObjects(ctx, bucket, minio.ListObjectsOptions{})
	for object := range objectCh {
		if object.Err != nil {
			response.StatusCode = http.StatusInternalServerError
			response.Message = "Error during minio#ListObjects"
			//TODO make sure this is safe
			//response.Error = object.Err.Error()

			return c.JSON(response.StatusCode, response)
		}

		response.Data.Keys = append(response.Data.Keys, object.Key)
	}

	response.StatusCode = http.StatusOK
	response.Message = "V1BucketRead ok"

	return c.JSON(response.StatusCode, response)
}
