//go:build ignore

package main

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

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

// One-off, tightly scoped fix for a single account stuck with the wrong
// app_users.configid (a pre-fix Staff/Rider row created before the
// UsersPanel.tsx / fiestaApi.ts configid bug was corrected). Only ever
// touches the one row matching this exact authname/email.
const targetEmail = "kmartuser@gmail.com"

func printRows(db *sql.DB, label string) {
	fmt.Printf("\n--- %s ---\n", label)
	rows, err := db.Query(`
		SELECT userid, authname, email, configid, roleid, tenantid, locationid, status
		FROM app_users
		WHERE lower(authname) = lower($1) OR lower(email) = lower($1)`, targetEmail)
	if err != nil {
		log.Fatalf("query error: %v", err)
	}
	defer rows.Close()

	found := false
	for rows.Next() {
		found = true
		var userid, configid, roleid, tenantid, locationid sql.NullInt64
		var authname, email, status sql.NullString
		if err := rows.Scan(&userid, &authname, &email, &configid, &roleid, &tenantid, &locationid, &status); err != nil {
			log.Fatalf("scan error: %v", err)
		}
		fmt.Printf("userid=%d authname=%q email=%q configid=%d roleid=%d tenantid=%d locationid=%d status=%q\n",
			userid.Int64, authname.String, email.String, configid.Int64, roleid.Int64, tenantid.Int64, locationid.Int64, status.String)
	}
	if !found {
		fmt.Println("NO ROW FOUND — account does not exist under this authname/email.")
	}
}

func main() {
	dsn := "host=66.116.207.225 port=5433 user=admin password=Package@123# dbname=nearledb sslmode=disable"
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		log.Fatalf("open error: %v", err)
	}
	defer db.Close()

	if err := db.Ping(); err != nil {
		log.Fatalf("ping error: %v", err)
	}
	fmt.Println("Connected to nearledb.")

	printRows(db, "BEFORE")

	res, err := db.Exec(`
		UPDATE app_users
		SET configid = 1
		WHERE (lower(authname) = lower($1) OR lower(email) = lower($1)) AND configid <> 1`, targetEmail)
	if err != nil {
		log.Fatalf("update error: %v", err)
	}
	n, _ := res.RowsAffected()
	fmt.Printf("\nRows updated: %d\n", n)

	printRows(db, "AFTER")
}
