package mysqlquerybuilder

import (
	"fmt"
	"regexp"
	"strings"
)

var datePattern = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}Z)?$`)

func isValidDateOrDateTime(value string) bool {
	return datePattern.MatchString(value)
}

func BuildFilterQuery(baseQuery, table string, filter map[string]interface{}) (string, []any) {
	var conditions []string
	var args []any

	for key, value := range filter {
		if strVal, ok := value.(string); ok && isValidDateOrDateTime(strVal) {
			conditions = append(conditions, fmt.Sprintf("DATE(%s.%s) = ?", table, key))
			args = append(args, strVal)
		} else {
			conditions = append(conditions, fmt.Sprintf("%s.%s = ?", table, key))
			args = append(args, value)
		}
	}

	query := baseQuery

	if len(conditions) > 0 {
		if strings.Contains(strings.ToUpper(baseQuery), "WHERE") {
			query += " AND "
		} else {
			query += " WHERE "
		}
		query += strings.Join(conditions, " AND ")
	}

	return query, args
}
