package database

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

	"volleyball/internal/player"
	"volleyball/internal/team"

	_ "github.com/lib/pq" // Import the PostgreSQL driver
)

const teamTable = `
	CREATE TABLE IF NOT EXISTS teams (
		id SERIAL PRIMARY KEY,
		player1_id uuid NOT NULL,	
		player2_id uuid NOT NULL,
		formation_date DATE NOT NULL DEFAULT CURRENT_DATE,
		FOREIGN KEY (player1_id) REFERENCES players(id),
		FOREIGN KEY (player2_id) REFERENCES players(id)
	);
`

var tableNames = []string{
	"players",
	"teams",
}

func CheckIfTablesExist(db *sql.DB) (bool, error) {
	for _, tableName := range tableNames {
		exists, err := tableExists(db, tableName)
		if err != nil {
			return false, fmt.Errorf("error checking if table %s exists: %w", tableName, err)
		}
		if !exists {
			return false, nil // At least one table does not exist
		}
	}
	return true, nil // All tables exist
}

// func tableExists(db *sql.DB, tableName string) (bool, error) {
// 	query := `
// 		SELECT EXISTS (
// 			SELECT FROM information_schema.tables
// 			WHERE table_schema = 'public' AND table_name = $1
// 		);
// 	`
// 	var exists bool
// 	err := db.QueryRow(query, tableName).Scan(&exists)
// 	return exists, err
// }

func InitTables(d *sql.DB) error {
	CreateOrUpdateTablePG(d, "users", player.User{})
	CreateOrUpdateTablePG(d, "roles", player.Roles{})
	createTable(d, "teams", team.Team{})
	createTable(d, "teams_player", team.TeamPlayerAssociation{})

	tables := []string{
		// player.PlayerTable,
		// player.RoleTable,
		teamTable,
	}

	for _, table := range tables {
		if _, err := d.Exec(table); err != nil {
			log.Fatalf("Error creating table: %v", err)
			return fmt.Errorf("error creating table: %w", err)
		}
	}

	log.Println("Tables initialized successfully.")
	return nil
}
