package shared

import (
	"context"
	"time"

	"github.com/rs/zerolog"
	"gorm.io/gorm/logger"
)

type ZerologGormAdapter struct {
	logger zerolog.Logger
}

func NewGormLogger(zerologger zerolog.Logger) *ZerologGormAdapter {
	return &ZerologGormAdapter{zerologger}
}

func (g *ZerologGormAdapter) LogMode(newLevel logger.LogLevel) logger.Interface {
	switch newLevel {
	case logger.Error:
		g.logger = g.logger.Level(zerolog.ErrorLevel)
	case logger.Warn:
		g.logger = g.logger.Level(zerolog.WarnLevel)
	case logger.Info:
		g.logger = g.logger.Level(zerolog.InfoLevel)
	case logger.Silent:
		g.logger = g.logger.Level(zerolog.Disabled)
	}
	return g
}
func (g *ZerologGormAdapter) Info(ctx context.Context, format string, args ...any) {
	g.logger.Info().Ctx(ctx).Msgf(format, args...)
}
func (g *ZerologGormAdapter) Warn(ctx context.Context, format string, args ...any) {
	g.logger.Warn().Ctx(ctx).Msgf(format, args...)
}
func (g *ZerologGormAdapter) Error(ctx context.Context, format string, args ...any) {
	g.logger.Error().Ctx(ctx).Msgf(format, args...)
}

func (g *ZerologGormAdapter) Trace(
	ctx context.Context,
	begin time.Time,
	fc func() (sql string, rowsAffected int64),
	err error,
) {
	sql, rowsAffected := fc()
	g.logger.Trace().
		Ctx(ctx).
		Time("gorm-begin", begin).
		Err(err).
		Str("gorm-query", sql).
		Int64("gorm-rows-affected", rowsAffected).
		Send()
}

func (g *ZerologGormAdapter) OverwriteLoggingLevel(new zerolog.Level) {
	g.logger = g.logger.Level(new)
}

func (g *ZerologGormAdapter) OverwriteLogger(new zerolog.Logger) {
	g.logger = new
}
