package testorder

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

	_ "github.com/lib/pq"
	"gitlab.ost.ch/marketminds/marketminds/pkg/entity"
)

func Test_Connect() {
	connStr := os.Getenv("DATABASE_URL")
	fmt.Println("Connecting to the database...", connStr)

	db, err := sql.Open("postgres", connStr)
	if err != nil {
		log.Fatal("Error connecting to the database: ", err)
	}

	// Try to ping the database to verify the connection
	err = db.Ping()
	if err != nil {
		log.Fatal("Error pinging database: ", err)
	}

	fmt.Println("Successfully connected to the database!")

	//createNewsChannel(db, Get_DB_TO_INSERT())
	getNewsChannels(db)
	//insert_test_name(db)
	//get_test_name(db)
	// Now you can perform database operations using the db object
	//insertTest(db, Test{Name: "test1", TestNumber: 1})
	//get_test_name_with_struct(db)
}

func Get_DB_TO_INSERT() entity.NewsChannel {
	channel := entity.NewNewsChannel(
		1,
		"http://example.com/rss",
		"http://example.com/image.jpg",
		"Example News Channel",
		"http://example.com",
		"An example news channel",
		"en",
		"© Example",
		time.Now(), // Example lastBuildDate
		time.Now(), // Example updatedAt
		time.Now(), // Example createdAt
	)
	return *channel
}

func insert_test_name(db *sql.DB) error {
	fmt.Println("Insert query:")

	_, err := db.Exec("INSERT INTO marketminds.test (name) VALUES ($1)", "test")
	if err != nil {
		log.Fatalln(err)
		fmt.Println("error in query")
	}

	return nil
}

func get_test_name(db *sql.DB) error {
	fmt.Println("Get query:")

	var name string
	var test_number int
	var news []string
	rows, err := db.Query("SELECT * FROM marketminds.test")
	defer rows.Close()
	if err != nil {
		log.Fatalln(err)
		fmt.Println("error in query")
	}

	for rows.Next() {
		rows.Scan(&name, &test_number)
		news = append(news, name)
		fmt.Println(name, test_number)
	}
	fmt.Println(news)

	return nil
}

type Test struct {
	Name       string
	TestNumber int
}

func insertTest(db *sql.DB, test Test) error {
	fmt.Println("Inserting test:", test)

	_, err := db.Exec("INSERT INTO marketminds.test (name, test_number) VALUES ($1, $2)", test.Name, test.TestNumber)
	if err != nil {
		log.Println(err)
	}

	fmt.Println("Test inserted successfully")
	return nil
}

func get_test_name_with_struct(db *sql.DB) error {
	fmt.Println("Get with struct")

	var tests []Test
	rows, err := db.Query("SELECT name, test_number FROM marketminds.test")
	defer rows.Close()
	if err != nil {
		log.Fatalln(err)
		fmt.Println("error in query")
	}

	for rows.Next() {
		var test Test
		if err := rows.Scan(&test.Name, &test.TestNumber); err != nil {
			log.Println(err)
			continue // Skip current row if scan fails
		}
		tests = append(tests, test)
		fmt.Println(test.Name, test.TestNumber)
	}

	return nil
}

func createNewsChannel(db *sql.DB, nc entity.NewsChannel) error {
	query := `
	INSERT INTO marketminds.newschannel(
		rssurl, imageurl, title, link, description, language, copyright, lastbuilddate, updatedat, createdat)
		VALUES
            ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) 
        `
	fmt.Println("Executing query:", query)

	_, err := db.Exec(query,
		nc.RssUrl, nc.ImageUrl, nc.Title, nc.Link, nc.Description,
		nc.Language, nc.Copyright, nc.LastBuildDate,
		nc.UpdatedAt, nc.CreatedAt)

	if err != nil {
		return fmt.Errorf("error inserting news channel: %v", err)
	}

	fmt.Println("Successfully inserted news channel:", nc.Title)
	return nil
}

func getNewsChannels(db *sql.DB) error {
	fmt.Println("Fetching news channels...")

	var newsChannels []entity.NewsChannel

	rows, err := db.Query("SELECT * FROM marketminds.newschannel")
	if err != nil {
		log.Fatal(err)
		return nil
	}
	defer rows.Close()

	for rows.Next() {
		var nc entity.NewsChannel
		err := rows.Scan(&nc.Id, &nc.RssUrl, &nc.ImageUrl, &nc.Title, &nc.Link, &nc.Description,
			&nc.Language, &nc.Copyright, &nc.LastBuildDate, &nc.UpdatedAt, &nc.CreatedAt)
		if err != nil {
			log.Println(err)
			continue
		}
		newsChannels = append(newsChannels, nc)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
		return nil
	}
	fmt.Println(newsChannels)
	fmt.Println("Successfully fetched news channels")
	return nil
}
