//go:build ignore

package main

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

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

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("Error opening db connection: %v", err)
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		log.Fatalf("Error pinging db: %v", err)
	}
	fmt.Println("Connected successfully to PostgreSQL!")

	// 1. Group users by roleid
	query1 := `
		SELECT roleid, COUNT(*), MIN(authname) AS sample_user
		FROM app_users
		GROUP BY roleid
		ORDER BY roleid;
	`
	rows1, err := db.Query(query1)
	if err != nil {
		log.Fatalf("Query1 error: %v", err)
	}
	defer rows1.Close()

	fmt.Println("\n--- USER COUNTS BY ROLEID ---")
	for rows1.Next() {
		var roleid sql.NullInt64
		var count int
		var sampleUser sql.NullString
		if err := rows1.Scan(&roleid, &count, &sampleUser); err != nil {
			log.Fatalf("Row scan error: %v", err)
		}
		fmt.Printf("Role ID: %5d | Count: %5d | Sample User: %s\n", roleid.Int64, count, sampleUser.String)
	}

	// 2. Fetch list of tables matching 'rider' or 'pool'
	query2 := `
		SELECT table_name
		FROM information_schema.tables
		WHERE table_name LIKE '%rider%' OR table_name LIKE '%pool%' OR table_name LIKE '%staff%';
	`
	rows2, err := db.Query(query2)
	if err != nil {
		log.Fatalf("Query2 error: %v", err)
	}
	defer rows2.Close()

	fmt.Println("\n--- RIDER/POOL/STAFF TABLES ---")
	for rows2.Next() {
		var tableName string
		if err := rows2.Scan(&tableName); err != nil {
			log.Fatalf("Row scan error: %v", err)
		}
		fmt.Println("Table Name:", tableName)
	}

	// 3. Check triggers on app_users
	query3 := `
		SELECT tgname, tgtype, pg_get_triggerdef(pg_trigger.oid)
		FROM pg_trigger
		JOIN pg_class ON pg_class.oid = tgrelid
		WHERE relname = 'app_users';
	`
	rows3, err := db.Query(query3)
	if err != nil {
		log.Fatalf("Query3 error: %v", err)
	}
	defer rows3.Close()

	fmt.Println("\n--- TRIGGERS ON app_users ---")
	for rows3.Next() {
		var tgname, tgdef string
		var tgtype int
		if err := rows3.Scan(&tgname, &tgtype, &tgdef); err != nil {
			log.Fatalf("Row scan error: %v", err)
		}
		fmt.Printf("Trigger: %s | Type: %d | Def: %s\n", tgname, tgtype, tgdef)
	}
}
