package data

import (
	"bsm/full/module/base/initial/internal/impl"
	"bsm/full/module/base/initial/internal/models"
	pb "bsm/full/module/base/initial/pb"
	"git.apinb.com/bsm-sdk/core/vars"
)

func GetAreasByCache(in *pb.AreasRequest) ([]*models.InitialAreas, error) {
	var areas []*models.InitialAreas

	var (
		key string
		val any
	)

	if in.GetCountryCode() != "" {
		key = "country_code = ?"
		val = in.GetCountryCode()
	} else if in.GetCountryId() != 0 {
		key = "country_id = ?"
		val = in.GetCountryId()
	}

	cacheKey := impl.RedisService.BuildKey("areas", key, val, in.ShowTown)

	err := impl.RedisService.Get(cacheKey, &areas)
	if err == nil {
		return areas, nil
	}

	err = impl.DBService.Where("enabled = ?", true).Where(key, val).Where("show_town = ?", in.ShowTown).
		Order("sort_order ASC, name ASC").
		Find(&areas).Error

	err = impl.RedisService.Set(cacheKey, areas, vars.DefaultTTL)
	return areas, err
}
