package legacy

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

	"ymhut-box/server/unified-management/internal/config"
	"ymhut-box/server/unified-management/internal/db"
)

func TestSaveValidateAndRestoreLegacyJSON(t *testing.T) {
	root := t.TempDir()
	public := filepath.Join(root, "public")
	if err := os.MkdirAll(public, 0o755); err != nil {
		t.Fatal(err)
	}
	path := filepath.Join(public, "media-types.json")
	if err := os.WriteFile(path, []byte(`{"layout_version":"1","categories":[]}`), 0o644); err != nil {
		t.Fatal(err)
	}
	cfg := &config.Config{
		StorageDir:      filepath.Join(root, "storage"),
		UpdatePublicDir: public,
		Database: config.DatabaseConfig{
			Provider:               "sqlite",
			SQLitePath:             filepath.Join(root, "storage", "unified.sqlite"),
			FailoverEnabled:        true,
			HealthIntervalSec:      3600,
			MaxOpenConns:           1,
			MaxIdleConns:           1,
			ConnMaxLifetimeSeconds: 60,
		},
	}
	store, err := db.Open(cfg)
	if err != nil {
		t.Fatal(err)
	}
	defer store.Close()
	service := NewService(cfg, store)
	if _, err := service.Validate(context.Background(), "media-types", SaveRequest{Raw: `{"not_categories":[]}`}); err == nil {
		t.Fatal("expected validation failure")
	}
	saved, err := service.Save(context.Background(), "media-types", SaveRequest{Raw: `{"categories":[{"id":"image","name":"Image","subcategories":[]}]}`, Note: "test"}, "admin")
	if err != nil {
		t.Fatal(err)
	}
	if saved.Parsed["layout_version"] == nil {
		t.Fatal("layout_version was not filled")
	}
	revisions, err := store.ListLegacyRevisions("media-types", 10)
	if err != nil {
		t.Fatal(err)
	}
	if len(revisions) < 2 {
		t.Fatalf("expected auto backup and saved revision, got %d", len(revisions))
	}
	restored, err := service.Restore(context.Background(), "media-types", revisions[len(revisions)-1].ID, "admin")
	if err != nil {
		t.Fatal(err)
	}
	if restored.Parsed["categories"] == nil {
		t.Fatal("restored document missing categories")
	}
}
