package queries

import (
	"strings"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/validator"

	"github.com/go-pg/pg/v10/orm"
	"github.com/pkg/errors"
)

type APICallsInterface interface {
	Insert(apiCall common.APICall) (orm.Result, error)
	Search(filter common.APICallsSearch, paging *PageQueryOptions) ([]common.APICall, int, error)
}

type APICalls struct {
	QueryBase
}

func (kv *APICalls) Insert(apiCall common.APICall) (orm.Result, error) {
	err := validator.ValidateStruct(apiCall)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	return kv.insert(&apiCall)
}

func (kv *APICalls) Search(filter common.APICallsSearch, paging *PageQueryOptions) ([]common.APICall, int, error) {
	calls := []common.APICall{}
	query := kv.GetDBConn().Model(&calls)

	kv.pageQuery(query, paging)
	kv.applyFilters(query, filter)
	count, err := query.SelectAndCount()
	if err != nil {
		return nil, 0, errors.WithStack(err)
	}

	return calls, count, nil
}

func (kv *APICalls) applyFilters(query *orm.Query, filter common.APICallsSearch) {
	if filter.Search != "" {
		search := strings.ToLower("%" + filter.Search + "%")
		query.Where("LOWER(client_id) LIKE ? "+
			"OR LOWER(endpoint) LIKE ? "+
			"OR LOWER(method) LIKE ?", search, search, search)
	}

	if filter.From != nil {
		query.Where("created_at >= ?", filter.From)
	}

	if filter.To != nil {
		query.Where("created_at <= ?", filter.To)
	}
}
