package api

import (
	"bytes"
	"context"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

	"github.com/go-chi/chi/v5"
	"golang.org/x/crypto/bcrypt"
)

func newMePasswordRouter(h *handlers) chi.Router {
	r := chi.NewRouter()
	r.Put("/api/me/password", h.handleChangePassword)
	return r
}

func TestChangePassword_Happy(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, "chpw1", "oldpassword1", false)

	body := `{"current_password":"oldpassword1","new_password":"newpassword1"}`
	req := httptest.NewRequest(http.MethodPut, "/api/me/password", bytes.NewReader([]byte(body)))
	req = withUser(req, user)
	rec := httptest.NewRecorder()
	newMePasswordRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusNoContent {
		t.Fatalf("status = %d, want 204; body=%s", rec.Code, rec.Body.String())
	}

	// Verify DB row was updated — new password should match.
	var hash string
	if err := pool.QueryRow(context.Background(),
		"SELECT password_hash FROM users WHERE id = $1", user.ID).Scan(&hash); err != nil {
		t.Fatalf("read hash: %v", err)
	}
	if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte("newpassword1")); err != nil {
		t.Errorf("new password does not match DB hash: %v", err)
	}
}

func TestChangePassword_WrongCurrent_401(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, "chpw2", "correctpw1", false)

	body := `{"current_password":"wrongpassword","new_password":"newpassword1"}`
	req := httptest.NewRequest(http.MethodPut, "/api/me/password", bytes.NewReader([]byte(body)))
	req = withUser(req, user)
	rec := httptest.NewRecorder()
	newMePasswordRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusUnauthorized {
		t.Errorf("status = %d, want 401 (wrong_password)", rec.Code)
	}
}

func TestChangePassword_TooShort_400(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, "chpw3", "somepassword1", false)

	body := `{"current_password":"somepassword1","new_password":"short"}`
	req := httptest.NewRequest(http.MethodPut, "/api/me/password", bytes.NewReader([]byte(body)))
	req = withUser(req, user)
	rec := httptest.NewRecorder()
	newMePasswordRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusBadRequest {
		t.Errorf("status = %d, want 400 (password_too_short)", rec.Code)
	}
}
