package api

import (
	"context"
	"net/http/httptest"
	"path/filepath"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/prism/proxy/internal/auth"
	"github.com/prism/proxy/internal/service"
	"github.com/prism/proxy/internal/store"
)

func TestAuthorizeRequestWithAPIKey(t *testing.T) {
	gin.SetMode(gin.TestMode)
	dir := t.TempDir()
	st, err := store.Open(filepath.Join(dir, "test.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { st.Close() })

	ctx := context.Background()
	if err := st.SetSettings(ctx, map[string]string{
		"auth_enabled":   "true",
		"admin_password": "secret",
	}); err != nil {
		t.Fatal(err)
	}

	raw, err := auth.GenerateAPIKey()
	if err != nil {
		t.Fatal(err)
	}
	if _, err := st.CreateAPIKey(ctx, "test", auth.APIKeyDisplayPrefix(raw), auth.HashAPIKey(raw)); err != nil {
		t.Fatal(err)
	}

	s := &Server{app: &service.App{Store: st}}
	settings, _ := st.GetSettings(ctx)

	w := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(w)
	c.Request = httptest.NewRequest("GET", "/api/v1/dashboard", nil)
	c.Request.Header.Set("X-API-Key", raw)
	if !s.authorizeRequest(c, settings) {
		t.Fatal("expected api key to authorize")
	}

	w2 := httptest.NewRecorder()
	c2, _ := gin.CreateTestContext(w2)
	c2.Request = httptest.NewRequest("GET", "/api/v1/dashboard", nil)
	c2.Request.Header.Set("Authorization", "Bearer "+raw)
	if !s.authorizeRequest(c2, settings) {
		t.Fatal("expected bearer api key to authorize")
	}

	w3 := httptest.NewRecorder()
	c3, _ := gin.CreateTestContext(w3)
	c3.Request = httptest.NewRequest("GET", "/api/v1/dashboard", nil)
	c3.Request.Header.Set("Authorization", "Bearer prism_invalid")
	if s.authorizeRequest(c3, settings) {
		t.Fatal("expected invalid key to fail")
	}
}
