package infra

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestOauth2Exchange_Success(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			t.Errorf("metodo = %s", r.Method)
		}
		if err := r.ParseForm(); err != nil {
			t.Fatalf("ParseForm: %v", err)
		}
		if got := r.PostForm.Get("grant_type"); got != "authorization_code" {
			t.Errorf("grant_type = %q", got)
		}
		if got := r.PostForm.Get("code"); got != "abc-code" {
			t.Errorf("code = %q", got)
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]any{
			"access_token":  "at-123",
			"refresh_token": "rt-456",
			"token_type":    "Bearer",
			"expires_in":    3600,
		})
	}))
	defer srv.Close()

	cfg := OAuthConfig{
		ClientID:     "c",
		ClientSecret: "s",
		TokenURL:     srv.URL,
		RedirectURL:  "http://r",
	}
	tokens, err := Oauth2Exchange(cfg, "abc-code")
	if err != nil {
		t.Fatalf("Oauth2Exchange: %v", err)
	}
	if tokens.AccessToken != "at-123" || tokens.RefreshToken != "rt-456" || tokens.TokenType != "Bearer" {
		t.Errorf("tokens = %+v", tokens)
	}
	if tokens.ExpiresAt == 0 {
		t.Error("ExpiresAt no deberia ser 0")
	}
}

func TestOauth2Exchange_EmptyCode(t *testing.T) {
	cfg := OAuthConfig{TokenURL: "http://x", ClientID: "c"}
	if _, err := Oauth2Exchange(cfg, ""); err == nil {
		t.Fatal("esperaba error con code vacio")
	}
}

func TestOauth2Exchange_ProviderError(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(400)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{
			"error":             "invalid_grant",
			"error_description": "code expired",
		})
	}))
	defer srv.Close()

	cfg := OAuthConfig{TokenURL: srv.URL, ClientID: "c"}
	if _, err := Oauth2Exchange(cfg, "code"); err == nil {
		t.Fatal("esperaba error del proveedor")
	}
}
