package auth

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestExchangeUsesAuthorizationCode(t *testing.T) {
	var gotBody, gotAgent, gotAccept string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotAgent = r.Header.Get("User-Agent")
		gotAccept = r.Header.Get("Accept")
		w.Header().Set("Content-Type", "application/json")
		switch r.URL.Path {
		case "/oauth/token":
			b, _ := io.ReadAll(r.Body)
			gotBody = string(b)
			_, _ = w.Write([]byte(`{"access_token":"tok","token_type":"Bearer","expires_in":86400,"user":{"id":7,"username":"Tim","avatar_url":"https://auth.timfalken.com/avatar/7?v=1"}}`))
		case "/api/me":
			if r.Header.Get("Authorization") != "Bearer tok" {
				t.Errorf("bearer %s", r.Header.Get("Authorization"))
			}
			_, _ = w.Write([]byte(`{"user":{"id":7,"username":"tim","is_admin":false,"email_verified":true,"avatar_url":"https://auth.timfalken.com/avatar/7?v=1"}}`))
		default:
			http.NotFound(w, r)
		}
	}))
	defer srv.Close()
	client := NewTimFalken(srv.URL, "git.timfalken.com", "geheim", "BlueGitAccountClient/0.1")
	id, err := client.Exchange(context.Background(), "code-1", "https://git.timfalken.com/auth/callback", "", "")
	if err != nil {
		t.Fatal(err)
	}
	if id.AuthID != 7 || id.Username != "tim" || id.AccessToken != "tok" || !id.EmailVerified {
		t.Fatalf("%+v", id)
	}
	if !strings.Contains(gotBody, "grant_type=authorization_code") || !strings.Contains(gotBody, "client_id=git.timfalken.com") || !strings.Contains(gotBody, "code=code-1") {
		t.Fatalf("body %s", gotBody)
	}
	if gotAgent != "BlueGitAccountClient/0.1" || gotAccept != "application/json" {
		t.Fatalf("headers %s %s", gotAgent, gotAccept)
	}
	url := client.AuthorizeURL("state-1", "nonce-1", "https://git.timfalken.com/auth/callback", "")
	if !strings.Contains(url, "/oauth/authorize?") || !strings.Contains(url, "state=state-1") {
		t.Fatal(url)
	}
}
