package postgres

import (
	"context"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/pkg/errors"
)

func NewPools(ctx context.Context, DSNs ...string) ([]*pgxpool.Pool, error) {
	pools := make([]*pgxpool.Pool, len(DSNs))

	for i, dsn := range DSNs {
		cfg, err := pgxpool.ParseConfig(dsn)
		if err != nil {
			closeOpened(pools[:i])

			return nil, errors.Wrap(err, "pgxpool.ParseConfig")
		}

		pool, err := pgxpool.NewWithConfig(ctx, cfg)
		if err != nil {
			closeOpened(pools[:i])

			return nil, errors.Wrap(err, "pgxpool.NewWithConfig")
		}

		pools[i] = pool
	}

	return pools, nil
}

func closeOpened(pools []*pgxpool.Pool) {
	for _, p := range pools {
		if p != nil {
			p.Close()
		}
	}
}
