package service

import (
	"github.com/UpmeshLTD/urus-aio/infrastructure/db/entities"
	"github.com/UpmeshLTD/urus-aio/mdm/server/http/dto"
	"github.com/gin-gonic/gin"
)

type iLocation interface {
	GetCountries(c *gin.Context)
	GetLocations(c *gin.Context)
}

// GetCountries godoc
// @Summary Get list of all countries.
// @Description Get list of all countries.
// @Tags Location
// @Accept */*
// @Produce json
// @Success 200 {object} dto.GetCountriesResponse
// @Router /countries [GET]
func (i *serviceImpl) GetCountries(c *gin.Context) {
	result, err := i.locationDomain.GetCountries(getCtx(c))
	if err != nil {
		responseInternalServerError(c, err)
		return
	}
	countriesDTO := make([]*dto.Country, 0, len(result))
	for _, v := range result {
		countriesDTO = append(countriesDTO, &dto.Country{
			ID:                v.ID.ID,
			InternationalName: v.InternationalName,
			LocalizedName:     v.LocalizedName,
			Code:              v.Code,
		})
	}
	responseSuccess(c, &dto.GetCountriesResponse{
		Data: countriesDTO,
	})
}

// GetLocations godoc
// @Summary Get list of children locations.
// @Description Get list of children locations.
// @Tags Location
// @Accept */*
// @Produce json
// @Param id path string true "Country ID / Country Code"
// @Param parentId query int false "Parent ID"
// @Success 200 {object} dto.GetLocationsResponse
// @Router /countries/{id}/locations [GET]
func (i *serviceImpl) GetLocations(c *gin.Context) {
	req := &dto.GetLocationsRequest{}
	if err := bindData(c, req, bindURI, bindQuery); err != nil {
		responseBadRequest(c, err)
		return
	}
	result, err := i.locationDomain.GetLocations(getCtx(c), &entities.GetLocationsFilterParams{
		CountryID: req.CountryID,
		ParentID:  req.ParentID,
	})
	if err != nil {
		responseInternalServerError(c, err)
		return
	}
	locationsDTO := make([]*dto.Location, 0, len(result))
	for _, v := range result {
		locationsDTO = append(locationsDTO, &dto.Location{
			ID:                v.ID.ID,
			InternationalName: v.InternationalName,
			LocalizedName:     v.LocalizedName,
			CountryID:         v.CountryID,
			ParentID:          v.ParentID,
		})
	}
	responseSuccess(c, &dto.GetLocationsResponse{
		Data: locationsDTO,
	})
}
