package location

import (
	"context"

	"gitlab.com/pactual1/backend/models"
	"gitlab.com/pactual1/backend/services/location/mapbox_lib"
)

type service struct {
	accessToken string
}

type Service interface {
	SearchPlace(context.Context, string) ([]*models.Place, error)
}

func NewService(accessToken string) Service {
	return service{accessToken: accessToken}
}

func (s service) SearchPlace(ctx context.Context, query string) ([]*models.Place, error) {
	geocoder := mapbox.NewFastHttpGeocoder(mapbox.AccessToken(s.accessToken))
	resp, err := geocoder.ForwardGeocode(ctx, &mapbox.ForwardGeocodeRequest{SearchText: query})
	if err != nil {
		return nil, err
	}
	var places []*models.Place
	for _, feature := range resp.Features {
		places = append(places, &models.Place{Text: feature.Text, Coordinates: feature.Geometry.Coordinates})
	}
	return places, nil
}
