package l4g

import (
	"os"
)

// dbWriter is the app-supplied sink that persists a log Entry to the database.
// The framework cannot import the app's repository, so the app registers a
// writer at startup via SetDatabaseWriter. If none is registered, the database
// logger falls back to the terminal so log lines are never silently dropped.
var dbWriter func(Entry) error

// SetDatabaseWriter registers the function the database logger uses to persist
// entries. Apps typically wire it to their repository:
//
//	l4g.SetDatabaseWriter(func(e l4g.Entry) error {
//	    return repository.InsertLogEntry(context.Background(), models.LogEntry(e))
//	})
func SetDatabaseWriter(w func(Entry) error) { dbWriter = w }

type DatabaseLogger struct{}

func NewDatabaseLogger() *DatabaseLogger {
	return &DatabaseLogger{}
}

func (d *DatabaseLogger) Write(entry Entry) error {
	if dbWriter == nil {
		return NewTerminalLogger().Write(entry)
	}
	return dbWriter(entry)
}

func (d *DatabaseLogger) Fatal(entry Entry) error {
	err := d.Write(entry)
	if err != nil {
		return err
	}
	os.Exit(1)
	return nil
}
