package database

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/lib/pq" // Import the PostgreSQL driver
)

type database struct {
	host     string
	port     int
	user     string
	password string
	dbname   string
	db       *sql.DB // Pointer to sql.DB
}

func (d *database) SetupTables() error {
	InitTables(d.db)
	log.Println("Database setup completed successfully.")
	return nil
}

func (d *database) GetDB() *sql.DB {
	if d.db == nil {
		log.Println("Database connection is not established. Call Connect() first.")
		return nil
	}
	return d.db
}

// New creates a new database instance with the provided configuration.
// It initializes the database connection parameters but does not connect to the database.
// This function should be called before calling Connect() to establish the connection.
// It returns a pointer to the database instance.
// Example usage:
// db := database.New("localhost", 5432, "user", "password", "dbname")
// It is intended to be used in the main application or setup phase.
// This function is not intended to be called during normal application operation.
// It is not intended to be called during normal application operation.
func New(host string, port int, user, password, dbname string) *database {
	return &database{
		host:     host,
		port:     port,
		user:     user,
		password: password,
		dbname:   dbname,
		db:       nil,
	}
}

func (d *database) Connect() (db *sql.DB) {
	fmt.Println("Connecting to the database...")
	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		d.host, d.port, d.user, d.password, d.dbname)
	// Construct the connection string

	db, err := sql.Open("postgres", psqlInfo)
	// Open a new database connection
	if err != nil {
		panic("failed to open database: " + err.Error())
		// return fmt.Errorf("failed to open database: %w", err)
	}

	// Test the connection
	if err := db.Ping(); err != nil {
		panic("failed to ping database: " + err.Error())
		// return fmt.Errorf("failed to ping database: %w", err)
	}

	log.Println("Connected to the database successfully")
	d.db = db
	return db
}
