package store

import "testing"

func TestChunkStatusUpsertGetOverwrite(t *testing.T) {
	s, _ := openTemp(t)

	if got, err := s.GetChunkStatus("book", 1, 0, "draft"); err != nil || got != nil {
		t.Fatalf("empty store must return (nil,nil), got %+v err=%v", got, err)
	}

	cs := ChunkStatus{
		BookID: "book", Chapter: 1, ChunkIdx: 0, Stage: "draft", SnapshotID: "snap1",
		Disposition: "flagged", FlagReason: "length", Attempts: 2, FinalHash: "",
		CostUSD: 0.0034, Detail: "truncated at max_tokens",
	}
	if err := s.UpsertChunkStatus(cs); err != nil {
		t.Fatal(err)
	}
	got, err := s.GetChunkStatus("book", 1, 0, "draft")
	if err != nil {
		t.Fatal(err)
	}
	if got == nil || got.Disposition != "flagged" || got.FlagReason != "length" || got.Attempts != 2 || got.CostUSD != 0.0034 {
		t.Fatalf("round-trip mismatch: %+v", got)
	}

	// Overwrite (the resolve semantics): a later verdict replaces the row.
	cs.Disposition, cs.FlagReason, cs.FinalHash, cs.CostUSD = "ok", "", "hashABC", 0.0068
	if err := s.UpsertChunkStatus(cs); err != nil {
		t.Fatal(err)
	}
	got, _ = s.GetChunkStatus("book", 1, 0, "draft")
	if got.Disposition != "ok" || got.FlagReason != "" || got.FinalHash != "hashABC" || got.CostUSD != 0.0068 {
		t.Fatalf("overwrite failed: %+v", got)
	}
}

func TestChunkStatusesForBookOrdered(t *testing.T) {
	s, _ := openTemp(t)
	rows := []ChunkStatus{
		{BookID: "b", Chapter: 2, ChunkIdx: 0, Stage: "draft", SnapshotID: "s", Disposition: "ok"},
		{BookID: "b", Chapter: 1, ChunkIdx: 1, Stage: "edit", SnapshotID: "s", Disposition: "skipped"},
		{BookID: "b", Chapter: 1, ChunkIdx: 0, Stage: "draft", SnapshotID: "s", Disposition: "flagged", FlagReason: "soft_refusal"},
		{BookID: "other", Chapter: 1, ChunkIdx: 0, Stage: "draft", SnapshotID: "s", Disposition: "ok"},
	}
	for _, r := range rows {
		if err := s.UpsertChunkStatus(r); err != nil {
			t.Fatal(err)
		}
	}
	got, err := s.ChunkStatusesForBook("b")
	if err != nil {
		t.Fatal(err)
	}
	if len(got) != 3 {
		t.Fatalf("want 3 rows for book b (other filtered), got %d", len(got))
	}
	// Ordered by (chapter, chunk_idx, stage).
	if got[0].Chapter != 1 || got[0].ChunkIdx != 0 || got[1].ChunkIdx != 1 || got[2].Chapter != 2 {
		t.Fatalf("ordering wrong: %+v", got)
	}
}
