package sql_driver

import (
	"database/sql"
	"fmt"
	"github.com/google/uuid"
	_ "github.com/mattn/go-sqlite3" // Import the SQLite3 driver
	"log"
)

func InitTables() {
	db, err := sql.Open("sqlite3", "./example.db")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Create a table
	createTableSQL := `
    CREATE TABLE IF NOT EXISTS users (
    	id TEXT NOT NULL PRIMARY KEY,
        name TEXT,
        age INTEGER
    );
    `
	_, err = db.Exec(createTableSQL)
	if err != nil {
		log.Fatalf("Error creating table: %s", err)
	}

	// Insert data into the table
	insertUserSQL := `INSERT INTO users (id, name, age) VALUES (?, ?, ?)`
	_, err = db.Exec(insertUserSQL, uuid.New(), "Alice", 30)
	if err != nil {
		log.Fatalf("Error inserting data: %s", err)
	}

	_, err = db.Exec(insertUserSQL, uuid.New(), "Bob", 25)
	if err != nil {
		log.Fatalf("Error inserting data: %s", err)
	}

	// Query the data
	queryUserSQL := `SELECT id, name, age FROM users`
	rows, err := db.Query(queryUserSQL)
	if err != nil {
		log.Fatalf("Error querying data: %s", err)
	}
	defer rows.Close()

	for rows.Next() {
		var id string
		var name string
		var age int
		err = rows.Scan(&id, &name, &age)
		if err != nil {
			log.Fatalf("Error scanning data: %s", err)
		}
		fmt.Printf("User: ID=%s, Name=%s, Age=%d\n", id, name, age)
	}

	// Update data
	updateUserSQL := `UPDATE users SET age = ? WHERE name = ?`
	_, err = db.Exec(updateUserSQL, 35, "Alice")
	if err != nil {
		log.Fatalf("Error updating data: %s", err)
	}

	// Verify the update
	fmt.Println("After update:")
	rows, err = db.Query(queryUserSQL)
	if err != nil {
		log.Fatalf("Error querying data: %s", err)
	}
	defer rows.Close()

	for rows.Next() {
		var id string
		var name string
		var age int
		err = rows.Scan(&id, &name, &age)
		if err != nil {
			log.Fatalf("Error scanning data: %s", err)
		}
		fmt.Printf("User: ID=%s, Name=%s, Age=%d\n", id, name, age)
	}
}
