package inifile

import (
	"os"
	"path/filepath"
	"testing"
)

func TestInit_Success(t *testing.T) {
	tmp := t.TempDir()
	path := filepath.Join(tmp, "playlists.ini")
	data := `[RU]
pls = http://example.com/ru.m3u
name = Russian Playlist
desc = Russian channels
src = public

[EN]
pls = http://example.com/en.m3u
name = English Playlist
`
	if err := os.WriteFile(path, []byte(data), 0644); err != nil {
		t.Fatal(err)
	}
	ini, err := Init(path)
	if err != nil {
		t.Fatal(err)
	}
	if len(ini.Lists) != 2 {
		t.Fatalf("expected 2 playlists, got %d", len(ini.Lists))
	}
	ru, ok := ini.Lists["RU"]
	if !ok {
		t.Fatal("expected RU playlist")
	}
	if ru.Name != "Russian Playlist" {
		t.Errorf("expected 'Russian Playlist', got '%s'", ru.Name)
	}
	if ru.Description != "Russian channels" {
		t.Errorf("expected 'Russian channels', got '%s'", ru.Description)
	}
	if ru.Url != "http://example.com/ru.m3u" {
		t.Errorf("expected URL, got '%s'", ru.Url)
	}
	if ru.Source != "public" {
		t.Errorf("expected 'public', got '%s'", ru.Source)
	}
}

func TestInit_NotFound(t *testing.T) {
	_, err := Init("/nonexistent/playlists.ini")
	if err == nil {
		t.Error("expected error for non-existent file")
	}
}

func TestInit_EmptyPls(t *testing.T) {
	tmp := t.TempDir()
	path := filepath.Join(tmp, "playlists.ini")
	data := `[BAD]
name = Bad Playlist
`
	os.WriteFile(path, []byte(data), 0644)
	ini, err := Init(path)
	if err != nil {
		t.Fatal(err)
	}
	if len(ini.Lists) != 0 {
		t.Errorf("expected 0 playlists (empty pls), got %d", len(ini.Lists))
	}
}

func TestInit_DefaultName(t *testing.T) {
	tmp := t.TempDir()
	path := filepath.Join(tmp, "playlists.ini")
	data := `[CODE1]
pls = http://example.com/list.m3u
`
	os.WriteFile(path, []byte(data), 0644)
	ini, err := Init(path)
	if err != nil {
		t.Fatal(err)
	}
	pls, ok := ini.Lists["CODE1"]
	if !ok {
		t.Fatal("expected CODE1 playlist")
	}
	if pls.Name != "Playlist #CODE1" {
		t.Errorf("expected 'Playlist #CODE1', got '%s'", pls.Name)
	}
}
