package oauth2

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestNotConfigured(t *testing.T) {
	g := NewGoogle("", "", "")
	if g.Configured() {
		t.Fatal("should not be configured")
	}
	if _, err := g.AuthCodeURL("s"); !errors.Is(err, ErrNotConfigured) {
		t.Fatalf("expected ErrNotConfigured, got %v", err)
	}
	if _, err := g.Exchange(context.Background(), "code"); !errors.Is(err, ErrNotConfigured) {
		t.Fatalf("expected ErrNotConfigured, got %v", err)
	}
}

func TestAuthCodeURL(t *testing.T) {
	g := NewGoogle("cid", "secret", "http://localhost/cb")
	u, err := g.AuthCodeURL("state-123")
	if err != nil {
		t.Fatal(err)
	}
	for _, want := range []string{"client_id=cid", "state=state-123", "response_type=code", "redirect_uri="} {
		if !contains(u, want) {
			t.Errorf("auth url missing %q: %s", want, u)
		}
	}
}

func TestExchangeFlow(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			t.Error(err)
		}
		if r.Form.Get("code") != "good-code" {
			t.Errorf("unexpected code %q", r.Form.Get("code"))
		}
		_, _ = w.Write([]byte(`{"access_token":"at-123","token_type":"Bearer"}`))
	})
	mux.HandleFunc("/userinfo", func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Authorization") != "Bearer at-123" {
			t.Errorf("unexpected auth header %q", r.Header.Get("Authorization"))
		}
		_, _ = w.Write([]byte(`{"sub":"1","email":"m-1@moe-dl.edu.my","name":"Aminah","picture":"http://img"}`))
	})
	srv := httptest.NewServer(mux)
	defer srv.Close()

	g := NewGoogle("cid", "secret", "http://localhost/cb")
	g.HTTP = srv.Client()
	g.tokenURL = srv.URL + "/token"
	g.userInfoURL = srv.URL + "/userinfo"

	info, err := g.Exchange(context.Background(), "good-code")
	if err != nil {
		t.Fatal(err)
	}
	if info.Email != "m-1@moe-dl.edu.my" || info.Name != "Aminah" {
		t.Fatalf("unexpected info: %+v", info)
	}
}

func contains(s, sub string) bool {
	return indexOf(s, sub) >= 0
}

func indexOf(s, sub string) int {
	for i := 0; i+len(sub) <= len(s); i++ {
		if s[i:i+len(sub)] == sub {
			return i
		}
	}
	return -1
}
