package sshd

import (
	"bytes"
	"context"
	"io"
	"testing"

	"gitlab.com/Timfa/bluegit/internal/store"
	"golang.org/x/crypto/ssh"
)

type memCh struct {
	in  bytes.Reader
	out bytes.Buffer
	err bytes.Buffer
}

func (m *memCh) Read(p []byte) (int, error)  { return m.in.Read(p) }
func (m *memCh) Write(p []byte) (int, error) { return m.out.Write(p) }
func (m *memCh) Close() error                { return nil }
func (m *memCh) CloseWrite() error           { return nil }
func (m *memCh) SendRequest(string, bool, []byte) (bool, error) {
	return true, nil
}
func (m *memCh) Stderr() io.ReadWriter { return &m.err }

func TestAPICommandUsesHook(t *testing.T) {
	var gotMethod, gotPath, gotBody string
	s := &Server{API: func(_ context.Context, user store.User, method, path string, body []byte) (int, []byte) {
		if user.Username != "ada" {
			t.Fatalf("user %s", user.Username)
		}
		gotMethod, gotPath, gotBody = method, path, string(body)
		return 200, []byte(`{"username":"ada"}`)
	}}
	ch := &memCh{}
	ch.in.Reset([]byte(`{"name":"x"}`))
	code := s.execGit(ch, store.User{Username: "ada"}, `api POST /api/v1/user/tokens`)
	if code != 0 || gotMethod != "POST" || gotPath != "/api/v1/user/tokens" || gotBody != `{"name":"x"}` {
		t.Fatalf("code %d %s %s %s", code, gotMethod, gotPath, gotBody)
	}
	if ch.out.String() != `{"username":"ada"}` || ch.err.String() != "status 200\n" {
		t.Fatalf("out %q err %q", ch.out.String(), ch.err.String())
	}

	ch = &memCh{}
	s.API = func(context.Context, store.User, string, string, []byte) (int, []byte) {
		return 403, []byte(`{"message":"nee"}`)
	}
	if s.execGit(ch, store.User{Username: "ada"}, "api GET /api/v1/projects") != 1 {
		t.Fatal("verwacht exit 1")
	}
	if ch.err.String() != "status 403\n" || ch.out.String() != `{"message":"nee"}` {
		t.Fatalf("out %q err %q", ch.out.String(), ch.err.String())
	}
	var _ ssh.Channel = ch
}
