package localdb

import (
	"path/filepath"
	"testing"
)

func TestRunLocalMigrationsBackfillsDefaultProject(t *testing.T) {
	dbPath := filepath.Join(t.TempDir(), "projects_backfill.db")

	local, err := New(dbPath)
	if err != nil {
		t.Fatalf("open localdb: %v", err)
	}
	t.Cleanup(func() { _ = local.Close() })

	cfg := &LocalConfiguration{
		UUID:             "cfg-without-project",
		Name:             "Cfg no project",
		Items:            LocalConfigItems{},
		SyncStatus:       "pending",
		OriginalUsername: "tester",
		IsActive:         true,
	}
	if err := local.SaveConfiguration(cfg); err != nil {
		t.Fatalf("save config: %v", err)
	}
	if err := local.DB().
		Model(&LocalConfiguration{}).
		Where("uuid = ?", cfg.UUID).
		Update("project_uuid", nil).Error; err != nil {
		t.Fatalf("clear project_uuid: %v", err)
	}
	if err := local.DB().Where("id = ?", "2026_02_06_projects_backfill").Delete(&LocalSchemaMigration{}).Error; err != nil {
		t.Fatalf("delete local migration record: %v", err)
	}

	if err := runLocalMigrations(local.DB()); err != nil {
		t.Fatalf("run local migrations: %v", err)
	}

	updated, err := local.GetConfigurationByUUID(cfg.UUID)
	if err != nil {
		t.Fatalf("get updated config: %v", err)
	}
	if updated.ProjectUUID == nil || *updated.ProjectUUID == "" {
		t.Fatalf("expected project_uuid to be backfilled")
	}

	project, err := local.GetProjectByUUID(*updated.ProjectUUID)
	if err != nil {
		t.Fatalf("get system project: %v", err)
	}
	if project.Name == nil || *project.Name != "Без проекта" {
		t.Fatalf("expected system project name, got %v", project.Name)
	}
	if !project.IsSystem {
		t.Fatalf("expected system project flag")
	}
}
