package notification

import (
	"context"
	"errors"
	"testing"

	"hfb_sys/backend/internal/database"
	"hfb_sys/backend/internal/model"
)

func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
	db := database.NewTestDB()
	if err := db.AutoMigrate(&model.Notification{}); err != nil {
		t.Fatalf("AutoMigrate() error = %v", err)
	}
	repo := NewRepository(db)
	ctx := context.Background()

	if err := db.Create(&model.Notification{
		UserID:  10,
		Type:    "order",
		Title:   "订单通知",
		Content: "请处理订单",
	}).Error; err != nil {
		t.Fatalf("Create() error = %v", err)
	}

	count, err := repo.UnreadCount(ctx, 10)
	if err != nil {
		t.Fatalf("UnreadCount() error = %v", err)
	}
	if count != 1 {
		t.Fatalf("UnreadCount() = %d, want 1", count)
	}

	if err := repo.MarkRead(ctx, 10, 1); err != nil {
		t.Fatalf("MarkRead() error = %v", err)
	}
	// 重复标记应保持幂等，不应误报不存在。
	if err := repo.MarkRead(ctx, 10, 1); err != nil {
		t.Fatalf("MarkRead() repeat error = %v", err)
	}

	count, err = repo.UnreadCount(ctx, 10)
	if err != nil {
		t.Fatalf("UnreadCount() after read error = %v", err)
	}
	if count != 0 {
		t.Fatalf("UnreadCount() after read = %d, want 0", count)
	}
}

func TestRepositoryMarkReadNotFound(t *testing.T) {
	db := database.NewTestDB()
	if err := db.AutoMigrate(&model.Notification{}); err != nil {
		t.Fatalf("AutoMigrate() error = %v", err)
	}
	repo := NewRepository(db)

	err := repo.MarkRead(context.Background(), 10, 99)
	if !errors.Is(err, ErrNotificationNotFound) {
		t.Fatalf("MarkRead() error = %v, want ErrNotificationNotFound", err)
	}
}
