package storage

import (
    "path/filepath"
    "testing"

	"safesight-control/internal/models"
)

func openTestStore(t *testing.T) *Store {
    t.Helper()
    store, err := OpenSQLite(filepath.Join(t.TempDir(), "app.db"))
    if err != nil {
        t.Fatalf("OpenSQLite: %v", err)
    }
    return store
}

func TestTasksRepoSavesAndLoadsTaskSnapshots(t *testing.T) {
    store := openTestStore(t)
    defer store.Close()

    repo := NewTasksRepo(store.DB())
    task := models.NewTask("task-1", "reload", []string{"edge-01"}, nil)
    task.Status = models.TaskSuccess
    task.Devices["edge-01"].Status = models.TaskSuccess
    task.Devices["edge-01"].Progress = 1

    if err := repo.Save(task); err != nil {
        t.Fatalf("Save: %v", err)
    }

    items, err := repo.List()
    if err != nil {
        t.Fatalf("List: %v", err)
    }
    if len(items) != 1 {
        t.Fatalf("expected one task, got %d", len(items))
    }
    if items[0].ID != "task-1" || items[0].Type != "reload" || items[0].Status != models.TaskSuccess {
        t.Fatalf("unexpected task snapshot: %#v", items[0])
    }
    if ds := items[0].Devices["edge-01"]; ds == nil || ds.Status != models.TaskSuccess || ds.Progress != 1 {
        t.Fatalf("unexpected device snapshot: %#v", items[0].Devices["edge-01"])
    }
}
