package usecase

import (
	"context"
	"testing"

	"apps/backend/internal/module/appnotif/repository"
)

func TestNotifyJobStatePreservesReadUntilTerminalChange(t *testing.T) {
	ctx := context.Background()
	const (
		ownerUID = int64(42)
		jobID    = "job-1"
		template = "compose_mimic"
	)
	repo := repository.NewMemory()
	service := New(repo)

	if err := service.NotifyJobState(ctx, ownerUID, jobID, template, "queued", "等待中", 0); err != nil {
		t.Fatal(err)
	}
	list, err := service.List(ctx, ownerUID)
	if err != nil || len(list) != 1 {
		t.Fatalf("list queued notification: len=%d err=%v", len(list), err)
	}
	if err := service.MarkRead(ctx, ownerUID, list[0].ID); err != nil {
		t.Fatal(err)
	}

	if err := service.NotifyJobState(ctx, ownerUID, jobID, template, "running", "處理中", 50); err != nil {
		t.Fatal(err)
	}
	list, _ = service.List(ctx, ownerUID)
	if list[0].ReadAt == 0 {
		t.Fatal("running progress made a read notification unread")
	}

	if err := service.NotifyJobState(ctx, ownerUID, jobID, template, "succeeded", "已完成", 100); err != nil {
		t.Fatal(err)
	}
	list, _ = service.List(ctx, ownerUID)
	if list[0].ReadAt != 0 {
		t.Fatal("new terminal state did not become unread")
	}
	if err := service.MarkRead(ctx, ownerUID, list[0].ID); err != nil {
		t.Fatal(err)
	}
	if err := service.NotifyJobState(ctx, ownerUID, jobID, template, "succeeded", "已完成", 100); err != nil {
		t.Fatal(err)
	}
	list, _ = service.List(ctx, ownerUID)
	if list[0].ReadAt == 0 {
		t.Fatal("duplicate terminal state made a read notification unread")
	}
}
