package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/alicebob/miniredis/v2"
	"github.com/ez-api/ez-api/internal/model"
	"github.com/ez-api/ez-api/internal/service"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func newTestAdminHandler(t *testing.T) (*AdminHandler, *gorm.DB, *miniredis.Miniredis) {
	t.Helper()
	gin.SetMode(gin.TestMode)

	dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())
	db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
	if err != nil {
		t.Fatalf("open sqlite: %v", err)
	}
	if err := db.AutoMigrate(&model.Master{}, &model.Key{}); err != nil {
		t.Fatalf("migrate: %v", err)
	}

	mr := miniredis.RunT(t)
	rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
	sync := service.NewSyncService(rdb)
	stats := service.NewStatsService(rdb)
	masterService := service.NewMasterService(db)
	return NewAdminHandler(db, db, masterService, sync, stats, nil), db, mr
}

func TestAdmin_BatchMasters_Status(t *testing.T) {
	h, db, mr := newTestAdminHandler(t)

	m := &model.Master{
		Name:         "m1",
		Group:        "default",
		Status:       "active",
		Epoch:        1,
		MaxChildKeys: 5,
		GlobalQPS:    3,
	}
	if err := db.Create(m).Error; err != nil {
		t.Fatalf("create master: %v", err)
	}

	r := gin.New()
	r.POST("/admin/masters/batch", h.BatchMasters)

	payload := map[string]any{
		"action": "status",
		"status": "suspended",
		"ids":    []uint{m.ID},
	}
	b, _ := json.Marshal(payload)
	req := httptest.NewRequest(http.MethodPost, "/admin/masters/batch", bytes.NewReader(b))
	req.Header.Set("Content-Type", "application/json")
	rr := httptest.NewRecorder()
	r.ServeHTTP(rr, req)

	if rr.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d body=%s", rr.Code, rr.Body.String())
	}

	var updated model.Master
	if err := db.First(&updated, m.ID).Error; err != nil {
		t.Fatalf("reload master: %v", err)
	}
	if updated.Status != "suspended" {
		t.Fatalf("expected status suspended, got %q", updated.Status)
	}
	if got := mr.HGet(fmt.Sprintf("auth:master:%d", m.ID), "status"); got != "suspended" {
		t.Fatalf("expected redis status suspended, got %q", got)
	}
}
