package repository

import (
	"backend-agenter/internal/config"
	"context"

	"github.com/jackc/pgx/v4/pgxpool"
	"go.uber.org/zap"
)

func NewClient(config *config.Postgres) (*pgxpool.Pool, error) {
	ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
	defer cancel()

	zap.S().Infof("Address postgres string: %s", config.GetAddr())

	conn, err := pgxpool.Connect(ctx, config.GetAddr())
	if err != nil {
		zap.S().Errorf("Error while connecting to postgres: %s", err.Error())
		return nil, err
	}

	err = conn.Ping(ctx)
	if err != nil {
		zap.S().Errorf("Error while making ping request to postgres: %s", err.Error())
		return nil, err
	}

	zap.S().Info("Successfully connected to postgres")
	return conn, nil
}
