// Package errlog provides optional logging helpers for gateway/internal/library/errors.
// Keep logging out of the core errors package so callers can use slog, zap, or any logger.
package errlog

import (
	"context"
	"log/slog"

	errs "gateway/internal/library/errors"
)

// Attrs builds structured fields for any logger from an *errs.Error.
func Attrs(e *errs.Error) []any {
	if e == nil {
		return nil
	}

	attrs := []any{
		"code", e.DisplayCode(),
		"scope", e.Scope(),
		"category", e.Category(),
		"detail", e.Detail(),
		"http_status", e.HTTPStatus(),
		"grpc_code", e.GRPCCode().String(),
	}
	if cause := e.Unwrap(); cause != nil {
		attrs = append(attrs, "cause", cause)
	}

	return attrs
}

// Log writes a structured log line for e using slog.
func Log(ctx context.Context, log *slog.Logger, level slog.Level, e *errs.Error, msg string, attrs ...any) {
	if log == nil || e == nil {
		return
	}

	args := append(Attrs(e), attrs...)
	log.Log(ctx, level, msg, args...)
}

// Error logs at slog.LevelError.
func Error(ctx context.Context, log *slog.Logger, e *errs.Error, msg string, attrs ...any) {
	Log(ctx, log, slog.LevelError, e, msg, attrs...)
}

// Warn logs at slog.LevelWarn.
func Warn(ctx context.Context, log *slog.Logger, e *errs.Error, msg string, attrs ...any) {
	Log(ctx, log, slog.LevelWarn, e, msg, attrs...)
}
