// Package logging is the shared structured logger used by the bot and the web
// panel. Every record is written to three sinks at once: the console (stderr),
// the rotating log file, and the `logs` table that powers the live log view in
// the admin panel.
package logging

import (
	"database/sql"
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/z/tg-apicreator-bot/internal/repository"
)

// Level is the severity of a log record.
type Level int

const (
	Debug Level = iota
	Info
	Warn
	Error
)

// Parse converts a config string ("debug", "info", ...) into a Level.
func Parse(s string) Level {
	switch s {
	case "debug", "DEBUG":
		return Debug
	case "warn", "warning", "WARN":
		return Warn
	case "error", "err", "ERROR":
		return Error
	default:
		return Info
	}
}

func (l Level) String() string {
	switch l {
	case Debug:
		return "debug"
	case Info:
		return "info"
	case Warn:
		return "warn"
	case Error:
		return "error"
	}
	return "info"
}

// Logger is safe for concurrent use.
type Logger struct {
	repo  *repository.Repository
	file  *os.File
	level Level
	mu    sync.Mutex
}

// New opens (or creates) the log file and returns a ready logger.
// filePath may be empty to disable file logging.
func New(repo *repository.Repository, filePath, level string) (*Logger, error) {
	l := &Logger{repo: repo, level: Parse(level)}

	if filePath != "" {
		if dir := filepath.Dir(filePath); dir != "" {
			if err := os.MkdirAll(dir, 0o755); err != nil {
				return nil, fmt.Errorf("create log dir: %w", err)
			}
		}
		f, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
		if err != nil {
			return nil, fmt.Errorf("open log file: %w", err)
		}
		l.file = f
	}
	return l, nil
}

// Close releases the log file.
func (l *Logger) Close() {
	if l.file != nil {
		_ = l.file.Close()
	}
}

func (l *Logger) log(lvl Level, source string, uid sql.NullInt64, format string, args ...any) {
	if lvl < l.level {
		return
	}
	msg := fmt.Sprintf(format, args...)
	line := fmt.Sprintf("%s [%s] [%s] %s\n",
		time.Now().Format("2006-01-02 15:04:05"), lvl.String(), source, msg)

	l.mu.Lock()
	_, _ = os.Stderr.WriteString(line)
	if l.file != nil {
		_, _ = l.file.WriteString(line)
	}
	l.mu.Unlock()

	if l.repo != nil {
		_ = l.repo.AddLog(lvl.String(), source, uid, msg)
	}
}

// Infof logs at info level without a user context.
func (l *Logger) Infof(source, format string, args ...any) {
	l.log(Info, source, sql.NullInt64{}, format, args...)
}

// Warnf logs at warn level without a user context.
func (l *Logger) Warnf(source, format string, args ...any) {
	l.log(Warn, source, sql.NullInt64{}, format, args...)
}

// Errorf logs at error level without a user context.
func (l *Logger) Errorf(source, format string, args ...any) {
	l.log(Error, source, sql.NullInt64{}, format, args...)
}

// InfofU logs at info level with a Telegram user id for audit.
func (l *Logger) InfofU(source string, uid int64, format string, args ...any) {
	l.log(Info, source, nullInt(uid), format, args...)
}

// WarnfU logs at warn level with a Telegram user id.
func (l *Logger) WarnfU(source string, uid int64, format string, args ...any) {
	l.log(Warn, source, nullInt(uid), format, args...)
}

// ErrorfU logs at error level with a Telegram user id.
func (l *Logger) ErrorfU(source string, uid int64, format string, args ...any) {
	l.log(Error, source, nullInt(uid), format, args...)
}

func nullInt(i int64) sql.NullInt64 {
	if i == 0 {
		return sql.NullInt64{}
	}
	return sql.NullInt64{Int64: i, Valid: true}
}
