package db

import (
	"context"
	"fmt"
	"music-server/pkg/models"
	"os"
	"strings"
)

func ClearSongs(gameId int) {
	if gameId == -1 {
		_, err := pool.Exec(context.Background(), "DELETE FROM song")
		if err != nil {
			_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
		}
	} else {
		_, err := pool.Exec(context.Background(), "DELETE FROM song where game_id=$1", gameId)
		if err != nil {
			_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
		}
	}
}

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

func FindSongsFromGame(id int) []models.SongData {
	rows, err := pool.Query(context.Background(),
		"SELECT song_name, path, times_played FROM song WHERE game_id = $1", id)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		return nil
	}

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

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

		songDataList = append(songDataList, models.SongData{
			GameId:      id,
			SongName:    songName,
			Path:        path,
			TimesPlayed: timesPlayed,
		})
	}
	return songDataList
}

func AddSongPlayed(id int, name string) {
	_, err := pool.Exec(context.Background(),
		"UPDATE song SET times_played=times_played+1 WHERE game_id=$1 AND song_name=$2", id, name)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

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

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

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

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

func RemoveBrokenSong(song models.SongData) {
	_, err := pool.Exec(context.Background(), "DELETE FROM song where path=$1", song.Path)
	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
	}
}

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

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