package postgres

import (
	"database/sql"
	"errors"
	"fmt"

	"github.com/XSAM/otelsql"
)

// Unregister releases an instrumentation registration. Returned by
// InstrumentDBStats so callers can detach metrics during shutdown.
type Unregister func() error

// InstrumentDBStats registers `database/sql` connection-pool metrics
// (`db.sql.connection.*`) for db. Statement spans are already attached at open
// time inside OpenPrimary/OpenReplicas — this function adds the meter-side
// instrumentation.
//
// The returned Unregister detaches the metric callbacks; callers usually
// invoke it during shutdown after closing db.
func InstrumentDBStats(db *sql.DB, opts ...Option) (Unregister, error) {
	if db == nil {
		return nil, errors.New("instrument postgres db stats: nil db")
	}

	resolved := evalOptions(opts)
	otelOpts := []otelsql.Option{otelsql.WithAttributes(dbSystemAttribute)}
	if resolved.meterProvider != nil {
		otelOpts = append(otelOpts, otelsql.WithMeterProvider(resolved.meterProvider))
	}

	reg, err := otelsql.RegisterDBStatsMetrics(db, otelOpts...)
	if err != nil {
		return nil, fmt.Errorf("instrument postgres db stats: %w", err)
	}
	return reg.Unregister, nil
}
