package cli

import (
	"path/filepath"
	"testing"
)

func TestSQLitePostImportLoadExport(t *testing.T) {
	root := t.TempDir()
	db, err := openSQLite(filepath.Join(root, ".osaet.db"))
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()

	if err := applySQLiteSchema(db); err != nil {
		t.Fatal(err)
	}

	publishedAt := "2026-05-28T12:00:00+08:00"
	post := postFile{
		Path: filepath.Join(root, defaultPostsDir, "hello.md"),
		Frontmatter: postFrontmatter{
			ID:          "post-1",
			Slug:        "hello",
			Title:       "Hello",
			Status:      "published",
			Tags:        []string{"go"},
			Version:     1,
			SlugSource:  "manual",
			PublishedAt: &publishedAt,
			CreatedAt:   "2026-05-28T11:00:00+08:00",
			UpdatedAt:   "2026-05-28T12:00:00+08:00",
		},
		Body: "Body\n",
	}

	if err := upsertSQLitePost(root, db, post); err != nil {
		t.Fatal(err)
	}

	posts, err := loadSQLitePosts(db)
	if err != nil {
		t.Fatal(err)
	}
	if len(posts) != 1 {
		t.Fatalf("loaded %d posts, want 1", len(posts))
	}
	if posts[0].Frontmatter.Slug != "hello" || posts[0].Body != "Body\n" {
		t.Fatalf("loaded post mismatch: %#v", posts[0])
	}

	exported, skipped, err := exportPostsToFilesCount(root, posts, false)
	if err != nil {
		t.Fatal(err)
	}
	if exported != 1 || skipped != 0 {
		t.Fatalf("exported=%d skipped=%d", exported, skipped)
	}

	read, err := readPostFile(filepath.Join(root, defaultPostsDir, "hello.md"))
	if err != nil {
		t.Fatal(err)
	}
	if read.Frontmatter.Title != "Hello" {
		t.Fatalf("exported title = %q", read.Frontmatter.Title)
	}
}
