package hostorg

import (
	"context"
	"testing"

	"hyapp-admin-server/internal/appctx"

	"github.com/DATA-DOG/go-sqlmock"
)

func TestUpdateManagerProfilePersistsStatus(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("new sqlmock: %v", err)
	}
	defer db.Close()

	status := "disabled"
	reader := NewReader(db, nil, nil)
	ctx := appctx.WithContext(context.Background(), "lalu")

	// 经理状态是 manager_profiles 的身份开关；PUT 传 status 时必须落到 UPDATE，否则前端刷新会重新读到旧状态。
	mock.ExpectExec(`(?s)UPDATE manager_profiles\s+SET updated_at_ms = \?, status = \?\s+WHERE app_code = \? AND user_id = \?`).
		WithArgs(sqlmock.AnyArg(), "disabled", "lalu", int64(1003)).
		WillReturnResult(sqlmock.NewResult(0, 1))
	mock.ExpectQuery(`(?s)SELECT COUNT\(DISTINCT mp\.user_id\).*FROM manager_profiles mp`).
		WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(int64(1)))
	mock.ExpectQuery(`(?s)SELECT mp\.user_id, COALESCE\(manager\.current_display_user_id, ''\).*FROM manager_profiles mp`).
		WillReturnRows(managerListRows().
			AddRow(int64(1003), "1003", "manager", "avatar.png", int64(7), "西亚区", "disabled", "+63",
				true, true, true, true, true, true, false, true, true, true, true,
				int64(0), int64(0), int64(1710000000000), int64(1710000001000)))

	item, err := reader.UpdateManagerProfile(ctx, 1003, 7, updateManagerRequest{Status: &status})
	if err != nil {
		t.Fatalf("update manager profile: %v", err)
	}
	if item.Status != "disabled" {
		t.Fatalf("manager status = %q, want disabled", item.Status)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatalf("sql expectations: %v", err)
	}
}

func TestUpdateManagerProfileRejectsInvalidStatus(t *testing.T) {
	db, _, err := sqlmock.New()
	if err != nil {
		t.Fatalf("new sqlmock: %v", err)
	}
	defer db.Close()

	status := "off"
	reader := NewReader(db, nil, nil)
	_, err = reader.UpdateManagerProfile(appctx.WithContext(context.Background(), "lalu"), 1003, 7, updateManagerRequest{Status: &status})
	if err == nil || err.Error() != "manager status is invalid" {
		t.Fatalf("invalid status error = %v", err)
	}
}

func managerListRows() *sqlmock.Rows {
	return sqlmock.NewRows([]string{
		"user_id",
		"current_display_user_id",
		"username",
		"avatar",
		"region_id",
		"region_name",
		"status",
		"contact_info",
		"can_grant_avatar_frame",
		"can_grant_vehicle",
		"can_grant_badge",
		"can_grant_vip",
		"can_update_user_level",
		"can_add_bd_leader",
		"can_manage_cross_region",
		"can_add_admin",
		"can_add_superadmin",
		"can_block_user",
		"can_transfer_user_country",
		"bd_leader_count",
		"last_invited_at_ms",
		"created_at_ms",
		"updated_at_ms",
	})
}
