package localdb

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

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

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

	createdAt := time.Date(2026, 2, 1, 10, 0, 0, 0, time.UTC)
	updatedAt := time.Date(2026, 2, 3, 12, 30, 0, 0, time.UTC)
	project := &LocalProject{
		UUID:          "project-1",
		OwnerUsername: "tester",
		Code:          "OPS-1",
		Variant:       "Lenovo",
		IsActive:      true,
		CreatedAt:     createdAt,
		UpdatedAt:     updatedAt,
		SyncStatus:    "synced",
	}

	if err := local.SaveProjectPreservingUpdatedAt(project); err != nil {
		t.Fatalf("save project: %v", err)
	}

	syncedAt := time.Date(2026, 3, 16, 8, 45, 0, 0, time.UTC)
	project.SyncedAt = &syncedAt
	project.SyncStatus = "synced"

	if err := local.SaveProjectPreservingUpdatedAt(project); err != nil {
		t.Fatalf("save project second time: %v", err)
	}

	stored, err := local.GetProjectByUUID(project.UUID)
	if err != nil {
		t.Fatalf("get project: %v", err)
	}
	if !stored.UpdatedAt.Equal(updatedAt) {
		t.Fatalf("updated_at changed during sync save: got %s want %s", stored.UpdatedAt, updatedAt)
	}
	if stored.SyncedAt == nil || !stored.SyncedAt.Equal(syncedAt) {
		t.Fatalf("synced_at not updated correctly: got %+v want %s", stored.SyncedAt, syncedAt)
	}
}
