package main

import "testing"

func TestCalculateEpisodeNumbers(t *testing.T) {
	db := openDatabaseSource(":memory:")

	// Ensure the DB is empty
	db.Query("delete from videos").MustExec()

	db.Query(`insert into videos (title, url, upload_date, year, episode, run) values
		('Video A', 'a', '2025-01-04', 2025, 10401, 1),
		('Video D', 'd', '2025-01-05', 2025, null, 2),
		('Video C', 'c', '2025-01-04', 2025, null, 2),
		('Video B', 'b', '2025-01-04', 2025, null, 2),
		('Video E', 'e', '2025-10-01', 2025, null, 3),
		('Old Video', 'z', '2020-12-31', 2020, 100, 1)`).MustExec()

	err := CalculateEpisodeNumbers(db)
	if err != nil {
		t.Error(err)
	}

	rows, err := db.Query("select title, episode from videos where year = 2025").ScanMulti()
	if err != nil {
		t.Error(err)
	}

	expectedList := []struct {
		Title   string
		Episode int
	}{
		{"Video A", 10401},
		{"Video D", 10501},
		{"Video C", 10403},
		{"Video B", 10402},
		{"Video E", 100101},
	}

	for _, expected := range expectedList {
		var title string
		var episode int
		rows.MustNext()
		err = rows.Scan(&title, &episode)
		if err != nil {
			t.Error(err)
		}

		if title != expected.Title {
			t.Errorf("Title is %s, expected %s", title, expected.Title)
		}
		if episode != expected.Episode {
			t.Errorf("Episode is %d, expected %d for video %s", episode, expected.Episode, title)
		}
	}
	rows.MustFinish()
}