package pkg

import (
	"context"
	"fmt"
	"os"

	"github.com/jackc/pgx/v5"
)

func UpdateServerStats(buildNumber int64) {

	//url := "postgres://username:password@localhost:5432/database_name"

	url := fmt.Sprintf(
		"postgres://%v:%v@%v:%v/%v",
		os.Getenv("DATABASE_USER"),
		os.Getenv("DATABASE_PASSWORD"),
		os.Getenv("DATABASE_HOST"),
		os.Getenv("DATABASE_PORT"),
		os.Getenv("DATABASE_DB"),
	)

	fmt.Println(url)

	ctx := context.Background()
	conn, err := pgx.Connect(ctx, url)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
		//os.Exit(1)
	}
	defer conn.Close(ctx)

	sql := `
    INSERT INTO public."serverStats" (id, build, "lastUpdate")
	VALUES ($1, $2, NOW())
	ON CONFLICT (id) DO UPDATE
		SET build = EXCLUDED.build,
		"lastUpdate" = NOW();
    `

	_, err = conn.Exec(ctx, sql, "serverStats", buildNumber)

	if err != nil {
		fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		//os.Exit(1)
	}

}
