package storage

import (
    "path/filepath"
    "testing"
)

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

    repo := NewResourcesRepo(store.DB())
    err = repo.Save(StandardResourceRecord{
        Name:         "face_gallery_v1",
        ResourceType: "face_gallery",
        Version:      "auto",
        SHA256:       "abc123",
        SizeBytes:    52428800,
        Description:  "默认人脸库",
        FilePath:     "resources/standard_resources/face_gallery_v1.db",
    })
    if err != nil {
        t.Fatalf("Save: %v", err)
    }

    items, err := repo.List()
    if err != nil {
        t.Fatalf("List: %v", err)
    }
    if len(items) != 1 || items[0].ResourceType != "face_gallery" || items[0].Version != "auto" {
        t.Fatalf("unexpected resources: %#v", items)
    }
}

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

    repo := NewResourcesRepo(store.DB())
    repo.Save(StandardResourceRecord{
        Name: "face_gallery_v1", ResourceType: "face_gallery",
        Version: "v1", SHA256: "abc",
    })
    repo.Save(StandardResourceRecord{
        Name: "ppe_dataset_v1", ResourceType: "dataset",
        Version: "v2", SHA256: "def",
    })

    items, err := repo.ListByType("face_gallery")
    if err != nil {
        t.Fatalf("ListByType: %v", err)
    }
    if len(items) != 1 || items[0].Name != "face_gallery_v1" {
        t.Fatalf("expected 1 face_gallery, got %#v", items)
    }
}

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

    repo := NewResourcesRepo(store.DB())
    repo.Save(StandardResourceRecord{
        Name: "face_gallery_v1", ResourceType: "face_gallery",
        Version: "v1", SHA256: "abc",
    })
    repo.Save(StandardResourceRecord{
        Name: "face_gallery_v1", ResourceType: "face_gallery",
        Version: "v2", SHA256: "xyz",
    })

    items, _ := repo.List()
    if len(items) != 1 || items[0].Version != "v2" || items[0].SHA256 != "xyz" {
        t.Fatalf("expected upserted record v2/xyz, got %#v", items)
    }
}
