package handlers_test

import (
	"context"
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/yan1h/agent-coding-workflow/internal/acp/handlers"
)

// 无 decider（nil）时回退到「默认拒绝」逻辑：优先选 reject 类选项。
func TestPermission_AutoReject(t *testing.T) {
	t.Parallel()
	h := handlers.NewPermissionHandler(nil)
	params := mustJSON(t, map[string]any{
		"sessionId": "x",
		"toolCall":  map[string]any{"name": "shell.exec"},
		"options": []any{
			map[string]any{"id": "allow_once"},
			map[string]any{"id": "reject_once"},
		},
	})
	res := h.Handle(context.Background(), handlers.SessionContext{}, "", params)
	require.Nil(t, res.Err)

	var out struct {
		Outcome struct {
			Selected struct {
				ID string `json:"id"`
			} `json:"selected"`
		} `json:"outcome"`
	}
	require.NoError(t, json.Unmarshal(res.OK, &out))
	assert.Equal(t, "reject_once", out.Outcome.Selected.ID)
}

// 无 reject 类选项且无 decider 时，默认拒绝（返回空 outcome，不再误选 allow）。
func TestPermission_NoRejectOption_DefaultsToReject(t *testing.T) {
	t.Parallel()
	h := handlers.NewPermissionHandler(nil)
	params := mustJSON(t, map[string]any{
		"sessionId": "x",
		"options": []any{
			map[string]any{"id": "allow_once"},
			map[string]any{"id": "allow_session"},
		},
	})
	res := h.Handle(context.Background(), handlers.SessionContext{}, "", params)
	require.Nil(t, res.Err)
	assert.JSONEq(t, `{"outcome":{}}`, string(res.OK))
}

func TestPermission_NoOptions_EmptyOutcome(t *testing.T) {
	t.Parallel()
	h := handlers.NewPermissionHandler(nil)
	params := mustJSON(t, map[string]any{"sessionId": "x"})
	res := h.Handle(context.Background(), handlers.SessionContext{}, "", params)
	require.Nil(t, res.Err)
	assert.JSONEq(t, `{"outcome":{}}`, string(res.OK))
}
