package database

import (
	"errors"
	"fmt"
	"music-server/internal/db"
	"os"
	"strings"
)

type SongData struct {
	GameId      int
	SongName    string
	Path        string
	TimesPlayed int
	FileName    string
}

var compareError = errors.New("no rows in result set")

func AddSong(song SongData) {
	_, err := db.Dbpool.Exec(db.Ctx,
		"INSERT INTO song(game_id, song_name, path, file_name) VALUES ($1, $2, $3, $4)",
		song.GameId, song.SongName, song.Path, song.FileName)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func CheckSong(songPath string) bool {
	var path string
	err := db.Dbpool.QueryRow(db.Ctx,
		"SELECT path FROM song WHERE path = $1", songPath).Scan(&path)
	if err != nil {
		if compareError.Error() != err.Error() {
			_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		}
	}
	return path != ""
}

func UpdateSong(songName string, fileName string, path string) {
	_, err := db.Dbpool.Exec(db.Ctx,
		"UPDATE song SET song_name=$1, file_name=$2 WHERE path = $3",
		songName, fileName, path)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

func FetchAllSongs() []SongData {
	rows, err := db.Dbpool.Query(db.Ctx,
		"SELECT song_name, path FROM song")
	if err != nil {
		if compareError.Error() != err.Error() {
			_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		}
		return nil
	}

	var songDataList []SongData
	for rows.Next() {
		var songName string
		var path string

		err := rows.Scan(&songName, &path)
		if err != nil {
			if compareError.Error() != err.Error() {
				_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
			}
		}

		songDataList = append(songDataList, SongData{
			SongName: songName,
			Path:     path,
		})
	}
	return songDataList
}

func RemoveBrokenSongs(songs []SongData) {
	joined := ""
	for _, song := range songs {
		joined += "'" + song.Path + "',"
	}
	joined = strings.TrimSuffix(joined, ",")

	_, err := db.Dbpool.Exec(db.Ctx, "DELETE FROM song where path in ($1)", joined)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}
