package mysqlquerybuilder

import (
	"fmt"
	"strings"
)

func BuildDeletedAtQuery(query, table string) string {
	deletedAtClause := fmt.Sprintf(" %s.deleted_at IS NULL ", table)

	if strings.Contains(query, "WHERE") {
		return appendStringAfter(query, "AND", deletedAtClause)
	}

	if strings.Contains(query, "ORDER") {
		return appendStringBefore(query, "WHERE", "ORDER", deletedAtClause)
	}
	return appendStringBefore(query, "WHERE", "LIMIT", deletedAtClause)
}

func appendStringBefore(s, operator, needle, appendage string) string {
	limitIndex := strings.Index(strings.ToUpper(s), needle)

	if limitIndex == -1 {
		return s + operator + appendage
	}
	return s[:limitIndex] + operator + appendage + s[limitIndex:]
}

func appendStringAfter(s, operator, appendage string) string {
	index := strings.Index(strings.ToUpper(s), "WHERE")

	spaceAfterTarget := strings.Index(s[index:], " ")
	if spaceAfterTarget == -1 {
		spaceAfterTarget = len(s) - index
	}

	return s[:index+spaceAfterTarget] + appendage + operator + s[index+spaceAfterTarget:]
}
