package es

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/elastic/go-elasticsearch/v7"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"github.com/opensearch-project/opensearch-go"
	//"github.com/elastic/go-elasticsearch/v7/esutil"
)

func CreateIndexIfAbsent(cli *elasticsearch.Client, index, template string) error {
	req := esapi.IndicesExistsRequest{
		Index: []string{index},
	}

	r, err := req.Do(context.Background(), cli)
	if err != nil {
		return err
	}
	defer r.Body.Close()

	if r.StatusCode == http.StatusNotFound {
		ireq := esapi.IndicesCreateRequest{
			Index: index,
			Body:  strings.NewReader(template),
		}

		resp, err := ireq.Do(context.Background(), cli)
		if err != nil {
			return err
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			body, _ := io.ReadAll(resp.Body)
			return fmt.Errorf("create index failed. code=%d, status=%s, body=%s", resp.StatusCode, resp.Status(), string(body))
		}
	}

	return nil
}

func CreateIndexIfAbsentAws(cli *opensearch.Client, index, template string) error {
	req := esapi.IndicesExistsRequest{
		Index: []string{index},
	}

	r, err := req.Do(context.Background(), cli)
	if err != nil {
		return err
	}
	defer r.Body.Close()

	if r.StatusCode == http.StatusNotFound {
		ireq := esapi.IndicesCreateRequest{
			Index: index,
			Body:  strings.NewReader(template),
		}

		resp, err := ireq.Do(context.Background(), cli)
		if err != nil {
			return err
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			body, _ := io.ReadAll(resp.Body)
			return fmt.Errorf("create index failed. code=%d, status=%s, body=%s", resp.StatusCode, resp.Status(), string(body))
		}
	}

	return nil
}
