package adminnotification

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.AdminNotification{}); err != nil {
		t.Fatalf("AutoMigrate() error = %v", err)
	}
	repo := NewRepository(db)
	ctx := context.Background()

	if err := db.Create(&model.AdminNotification{
		AdminUserID: 7,
		Type:        "system",
		Title:       "库存预警",
		Content:     "二维码库存不足",
	}).Error; err != nil {
		t.Fatalf("Create() error = %v", err)
	}

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

	if err := repo.MarkRead(ctx, 7, 1); err != nil {
		t.Fatalf("MarkRead() error = %v", err)
	}
	if err := repo.MarkRead(ctx, 7, 1); err != nil {
		t.Fatalf("MarkRead() repeat error = %v", err)
	}

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

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

	rows := []model.AdminNotification{
		{AdminUserID: 7, Type: "system", Title: "一", Content: "一"},
		{AdminUserID: 7, Type: "system", Title: "二", Content: "二"},
		{AdminUserID: 8, Type: "system", Title: "三", Content: "三"},
	}
	if err := db.Create(&rows).Error; err != nil {
		t.Fatalf("Create() error = %v", err)
	}

	affected, err := repo.MarkAllRead(ctx, 7)
	if err != nil {
		t.Fatalf("MarkAllRead() error = %v", err)
	}
	if affected != 2 {
		t.Fatalf("MarkAllRead() affected = %d, want 2", affected)
	}
	affected, err = repo.MarkAllRead(ctx, 7)
	if err != nil {
		t.Fatalf("MarkAllRead() repeat error = %v", err)
	}
	if affected != 0 {
		t.Fatalf("MarkAllRead() repeat affected = %d, want 0", affected)
	}

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

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

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