package main

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

	_ "github.com/lib/pq"
)

func main() {
	dsn := "host=31.97.228.132 user=admin password=Package@321# dbname=logistics port=5433 sslmode=disable"
	db, err := sql.Open("postgres", dsn)
	if err != nil {
		log.Fatalf("Open failed: %v", err)
	}
	defer db.Close()

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

	// 1. Show pickupbookings columns + nullability
	fmt.Println("\n--- pickupbookings columns ---")
	rows, err := db.Query(`
		SELECT column_name, data_type, is_nullable, column_default
		FROM information_schema.columns
		WHERE table_schema = 'public' AND table_name = 'pickupbookings'
		ORDER BY ordinal_position
	`)
	if err != nil {
		log.Fatalf("Column query failed: %v", err)
	}
	defer rows.Close()
	for rows.Next() {
		var col, dtype, nullable string
		var def sql.NullString
		rows.Scan(&col, &dtype, &nullable, &def)
		fmt.Printf("  %-30s %-20s nullable=%-3s default=%s\n", col, dtype, nullable, def.String)
	}

	// 2. Show check constraints
	fmt.Println("\n--- check constraints on pickupbookings ---")
	crows, err := db.Query(`
		SELECT con.conname, pg_get_constraintdef(con.oid)
		FROM pg_constraint con
		JOIN pg_class rel ON rel.oid = con.conrelid
		WHERE rel.relname = 'pickupbookings' AND con.contype = 'c'
	`)
	if err != nil {
		log.Fatalf("Constraint query failed: %v", err)
	}
	defer crows.Close()
	for crows.Next() {
		var name, def string
		crows.Scan(&name, &def)
		fmt.Printf("  %s: %s\n", name, def)
	}
	fmt.Println("  (none if blank)")

	// 3. Attempt a raw INSERT to see the exact Postgres error
	fmt.Println("\n--- Attempting raw INSERT ---")
	_, insertErr := db.Exec(`
		INSERT INTO pickupbookings
		  (bookingno, appcustomerid, pickupaddress, pickuppincode, pickuplatitude, pickuplongitude,
		   deliveryaddress, deliverypincode, deliverylatitude, deliverylongitude,
		   bookingsource, status, createdat, updatedat)
		VALUES
		  ('DM-BK-DEBUG-001', 1, '123 Test St', '641012', 11.0168, 76.9558,
		   '', '', 0.0, 0.0,
		   'Customer_App', 'Pending_Pickup', NOW(), NOW())
	`)
	if insertErr != nil {
		fmt.Printf("INSERT ERROR: %v\n", insertErr)
	} else {
		fmt.Println("INSERT succeeded!")
		// Clean up
		db.Exec("DELETE FROM pickupbookings WHERE bookingno = 'DM-BK-DEBUG-001'")
		fmt.Println("Cleaned up test row.")
	}
}
