package team

import (
	"database/sql"
	"log"
)

type Team struct {
	UUID        string `db:"uuid" sql:"VARCHAR(255)" index:"true"`
	Name        string `db:"name" sql:"VARCHAR(100)"`
	OwnerUUID   string `db:"owner_uuid" sql:"VARCHAR(255)" index:"true"`
	Description string `db:"describtion" sql:"VARCHAR(255)"`
}

type TeamPlayerAssociation struct {
	TeamUUID   string `db:"team_uuid" sql:"VARCHAR(255)" index:"true"`
	PlayerUUID string `db:"player_uuid" sql:"VARCHAR(255)" index:"true"`
}

func GetAllTeams(db *sql.DB) ([]Team, error) {
	var teams []Team
	rows, err := db.Query("SELECT * FROM teams")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var team Team
		if err := rows.Scan(&team.UUID, &team.Name, &team.OwnerUUID, &team.Description); err != nil {
			return nil, err
		}
		teams = append(teams, team)
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}
	return teams, nil
}

func saveTeam(db *sql.DB, team Team) error {

	stmt := "INSERT INTO public.teams (name, owner_uuid,description) VALUES ($1, $2, $3)"
	log.Printf("Generated SQL statement: %s", stmt)
	_, err := db.Exec(stmt, team.Name, team.OwnerUUID, team.Description)
	if err != nil {
		log.Printf("Error saving team to database: %v", err)
	}
	log.Printf("Team %s saved to database", team.Name)
	return nil
}

func updateTeam(db *sql.DB, team Team) error {
	stmt := "UPDATE public.teams SET name = $1, description = $2 WHERE uuid = $3"
	_, err := db.Exec(stmt, team.Name, team.Description, team.UUID)
	if err != nil {
		log.Printf("Error updating team in database: %v", err)
		return err
	}
	log.Printf("Team %s updated successfully", team.Name)
	return nil

}
