package ai_summarizer

import (
	"errors"
	"fmt"
)

// logMinIOFailure records a structured log for a MinIO error and returns a wrapped
// error suitable for callers (connection issues include ErrMinIOUnavailable).
func (s *StorageClient) logMinIOFailure(operation string, err error, fields map[string]interface{}) error {
	if err == nil {
		return nil
	}
	if fields == nil {
		fields = make(map[string]interface{}, 4)
	}
	fields["endpoint"] = s.config.MinioEndpoint
	fields["bucket"] = s.config.MinioBucket
	fields["operation"] = operation
	fields["error"] = err.Error()

	switch {
	case isMinioConnectionError(err):
		fields["failure_type"] = "connection"
		s.logger.Error("MinIO connection unavailable", fields)
		return wrapMinIOError(err)
	case errors.Is(err, ErrBucketNotFound):
		fields["failure_type"] = "bucket_not_found"
		s.logger.Error("MinIO bucket not found", fields)
		return err
	default:
		fields["failure_type"] = "storage"
		s.logger.Error("MinIO operation failed", fields)
		return err
	}
}

// logMinIOFailuref is like logMinIOFailure with a formatted message prefix on the error.
func (s *StorageClient) logMinIOFailuref(operation string, err error, fields map[string]interface{}, format string, args ...interface{}) error {
	if err == nil {
		return nil
	}
	wrapped := fmt.Errorf(format+": %w", append(args, err)...)
	return s.logMinIOFailure(operation, wrapped, fields)
}
