package logs

import (
	"context"
	"github.com/uptrace/bun"
	"strings"
	"time"
)

type QueryHook struct {
	Debug bool
}

func (d QueryHook) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context {
	return ctx
}

func (d QueryHook) AfterQuery(_ context.Context, event *bun.QueryEvent) {
	sqlQuery := event.Query

	queryDuration := time.Now().Sub(event.StartTime)

	queryPrefixesToIgnore := []string{"SELECT", "BEGIN", "COMMIT"}
	shouldLogQuery := !strings.Contains(sqlQuery, "api_key")
	if shouldLogQuery {
		for _, prefixToIgnore := range queryPrefixesToIgnore {
			if strings.HasPrefix(sqlQuery, prefixToIgnore) {
				shouldLogQuery = false
				break
			}
		}
	}

	if d.Debug || shouldLogQuery {
		InfoWithFields(map[string]interface{}{"sql`": sqlQuery, "t": queryDuration.String()}, "")
	}
	return
}