package searchrepo

import (
	"bytes"
	"fmt"
	"io"
	"net/http"

	"git.ma-al.com/goc_daniel/b2b/app/config"
	"git.ma-al.com/goc_daniel/b2b/app/model"
)

type SearchProxyResponse struct {
	StatusCode int
	Body       []byte
}

type UISearchRepo interface {
	Search(index string, body []byte) (*SearchProxyResponse, error)
	GetIndexSettings(index string) (*SearchProxyResponse, error)
	GetRoutes(langId uint) ([]model.Route, error)
}

type SearchRepo struct {
	cfg *config.Config
}

func New() UISearchRepo {
	return &SearchRepo{
		cfg: config.Get(),
	}
}

func (r *SearchRepo) Search(index string, body []byte) (*SearchProxyResponse, error) {
	url := fmt.Sprintf("%s/indexes/%s/search", r.cfg.MailiSearch.ServerURL, index)
	return r.doRequest(http.MethodPost, url, body)
}

func (r *SearchRepo) GetIndexSettings(index string) (*SearchProxyResponse, error) {
	url := fmt.Sprintf("%s/indexes/%s/settings", r.cfg.MailiSearch.ServerURL, index)
	return r.doRequest(http.MethodGet, url, nil)
}

func (r *SearchRepo) doRequest(method, url string, body []byte) (*SearchProxyResponse, error) {
	var reqBody *bytes.Reader
	if body != nil {
		reqBody = bytes.NewReader(body)
	} else {
		reqBody = bytes.NewReader([]byte{})
	}

	req, err := http.NewRequest(method, url, reqBody)
	if err != nil {
		return nil, fmt.Errorf("failed to create request: %w", err)
	}

	req.Header.Set("Content-Type", "application/json")
	if r.cfg.MailiSearch.ApiKey != "" {
		req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.cfg.MailiSearch.ApiKey))
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("failed to reach meilisearch: %w", err)
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response: %w", err)
	}

	return &SearchProxyResponse{
		StatusCode: resp.StatusCode,
		Body:       respBody,
	}, nil
}

func (r *SearchRepo) GetRoutes(langId uint) ([]model.Route, error) {
	return nil, nil
}
