package api

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

	"github.com/go-chi/chi/v5"
)

func newMeTokenRouter(h *handlers) chi.Router {
	r := chi.NewRouter()
	r.Get("/api/me/api-token", h.handleGetMyAPIToken)
	r.Post("/api/me/api-token", h.handleRegenerateMyAPIToken)
	return r
}

func TestGetAPIToken_ReturnsCurrentToken(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "tok1", "pw", false)

	req := httptest.NewRequest(http.MethodGet, "/api/me/api-token", nil)
	req = withUser(req, user)
	rec := httptest.NewRecorder()
	newMeTokenRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	var resp apiTokenResp
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if resp.APIToken != user.ApiToken {
		t.Errorf("api_token = %q, want %q", resp.APIToken, user.ApiToken)
	}
}

func TestRegenerateAPIToken_IssuesNewToken(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "tok2", "pw", false)
	oldToken := user.ApiToken

	req := httptest.NewRequest(http.MethodPost, "/api/me/api-token", nil)
	req = withUser(req, user)
	rec := httptest.NewRecorder()
	newMeTokenRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	var resp apiTokenResp
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if resp.APIToken == "" {
		t.Fatalf("api_token is empty")
	}
	if resp.APIToken == oldToken {
		t.Errorf("api_token unchanged after regenerate")
	}

	// Verify DB row has the new token and old token no longer matches.
	var dbToken string
	if err := pool.QueryRow(context.Background(),
		"SELECT api_token FROM users WHERE id = $1", user.ID).Scan(&dbToken); err != nil {
		t.Fatalf("read token: %v", err)
	}
	if dbToken != resp.APIToken {
		t.Errorf("DB api_token = %q, want %q", dbToken, resp.APIToken)
	}
	if dbToken == oldToken {
		t.Errorf("old token still in DB after regenerate")
	}
}
