package api

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

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

	"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
)

func newAdminUsersRouter(h *handlers) chi.Router {
	r := chi.NewRouter()
	r.Route("/api/admin", func(admin chi.Router) {
		admin.Use(auth.RequireAdmin())
		admin.Get("/users", h.handleAdminListUsers)
		admin.Put("/users/{id}/admin", h.handleUpdateUserAdmin)
		// U2 additions:
		admin.Post("/users", h.handleAdminCreateUser)
		admin.Delete("/users/{id}", h.handleAdminDeleteUser)
		admin.Post("/users/{id}/reset-password", h.handleAdminResetPassword)
		admin.Put("/users/{id}/auto-approve", h.handleAdminAutoApproveToggle)
	})
	return r
}

func TestAdminUsers_List(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	admin := seedUser(t, pool, "listadmin", "pw", true)

	req := httptest.NewRequest(http.MethodGet, "/api/admin/users", nil)
	req = withUser(req, admin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	var resp struct {
		Users []struct{ Username string } `json:"users"`
	}
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if len(resp.Users) == 0 {
		t.Errorf("users list is empty; expected at least the seeded admin")
	}
}

func TestAdminUsers_Promote(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	admin := seedUser(t, pool, "promadmin", "pw", true)
	target := seedUser(t, pool, "promtarget", "pw", false)

	body := `{"is_admin": true}`
	req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/admin",
		bytes.NewReader([]byte(body)))
	req = withUser(req, admin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	var isAdmin bool
	if err := pool.QueryRow(context.Background(),
		"SELECT is_admin FROM users WHERE id = $1", target.ID).Scan(&isAdmin); err != nil {
		t.Fatalf("verify: %v", err)
	}
	if !isAdmin {
		t.Errorf("target not promoted")
	}
}

func TestAdminUsers_Demote_LastAdmin_Refused(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	// Reset to ensure exactly one admin exists.
	if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil {
		t.Fatalf("reset: %v", err)
	}
	soleAdmin := seedUser(t, pool, "soleadmin", "pw", true)

	body := `{"is_admin": false}`
	req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(soleAdmin.ID)+"/admin",
		bytes.NewReader([]byte(body)))
	req = withUser(req, soleAdmin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusConflict {
		t.Errorf("status = %d, want 409 (last_admin guard)", rec.Code)
	}
}

func TestAdminUsers_Demote_OtherAdmin_Allowed(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil {
		t.Fatalf("reset: %v", err)
	}
	caller := seedUser(t, pool, "caller", "pw", true)
	target := seedUser(t, pool, "targetadmin", "pw", true)

	body := `{"is_admin": false}`
	req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/admin",
		bytes.NewReader([]byte(body)))
	req = withUser(req, caller)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Errorf("status = %d, want 200 (two admins exist; demoting one is fine); body=%s", rec.Code, rec.Body.String())
	}
}

func TestAdminCreateUser_Happy(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	admin := seedUser(t, pool, "creator", "pw", true)

	body := `{"username":"newuser1","password":"abcd1234","is_admin":false}`
	req := httptest.NewRequest(http.MethodPost, "/api/admin/users", bytes.NewReader([]byte(body)))
	req = withUser(req, admin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	var resp adminUserView
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if resp.Username != "newuser1" || resp.IsAdmin {
		t.Errorf("response unexpected: %+v", resp)
	}
}

func TestAdminCreateUser_DuplicateUsername_409(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	admin := seedUser(t, pool, "duper", "pw", true)
	seedUser(t, pool, "existing", "pw", false)

	// seedUser prefixes usernames with dbtest.TestUserPrefix, so the
	// row above is "test-existing"; POST that exact name to actually
	// collide (stays test-prefixed for ResetDB).
	body := `{"username":"test-existing","password":"abcd1234"}`
	req := httptest.NewRequest(http.MethodPost, "/api/admin/users", bytes.NewReader([]byte(body)))
	req = withUser(req, admin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusConflict {
		t.Errorf("status = %d, want 409", rec.Code)
	}
}

func TestAdminDeleteUser_Happy(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	admin := seedUser(t, pool, "delcaller", "pw", true)
	target := seedUser(t, pool, "deltarget", "pw", false)

	req := httptest.NewRequest(http.MethodDelete, "/api/admin/users/"+uuidToString(target.ID), nil)
	req = withUser(req, admin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusNoContent {
		t.Errorf("status = %d, want 204", rec.Code)
	}
	var count int
	if err := pool.QueryRow(context.Background(),
		"SELECT count(*) FROM users WHERE id = $1", target.ID).Scan(&count); err != nil {
		t.Fatalf("verify: %v", err)
	}
	if count != 0 {
		t.Errorf("user still exists after delete (count=%d)", count)
	}
}

func TestAdminDeleteUser_LastAdmin_Refused(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil {
		t.Fatalf("reset: %v", err)
	}
	soleAdmin := seedUser(t, pool, "soleadmin", "pw", true)

	req := httptest.NewRequest(http.MethodDelete, "/api/admin/users/"+uuidToString(soleAdmin.ID), nil)
	req = withUser(req, soleAdmin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusConflict {
		t.Errorf("status = %d, want 409 (last_admin)", rec.Code)
	}
}

func TestAdminResetPassword_Happy(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	admin := seedUser(t, pool, "rcaller", "pw", true)
	target := seedUser(t, pool, "rtarget", "oldpw1234", false)

	body := `{"password":"newpassword1"}`
	req := httptest.NewRequest(http.MethodPost, "/api/admin/users/"+uuidToString(target.ID)+"/reset-password",
		bytes.NewReader([]byte(body)))
	req = withUser(req, admin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusNoContent {
		t.Errorf("status = %d, want 204; body=%s", rec.Code, rec.Body.String())
	}
	// Old password should no longer match.
	var hash string
	if err := pool.QueryRow(context.Background(),
		"SELECT password_hash FROM users WHERE id = $1", target.ID).Scan(&hash); err != nil {
		t.Fatalf("read hash: %v", err)
	}
	if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte("oldpw1234")); err == nil {
		t.Errorf("old password still matches; reset did nothing")
	}
}

func TestAdminResetPassword_TooShort_400(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	admin := seedUser(t, pool, "rsadm", "pw", true)
	target := seedUser(t, pool, "rstgt", "pw", false)

	body := `{"password":"abc"}`
	req := httptest.NewRequest(http.MethodPost, "/api/admin/users/"+uuidToString(target.ID)+"/reset-password",
		bytes.NewReader([]byte(body)))
	req = withUser(req, admin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

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

func TestAdminAutoApproveToggle(t *testing.T) {
	if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
		t.Skip("MINSTREL_TEST_DATABASE_URL not set")
	}
	h, pool := testHandlers(t)
	admin := seedUser(t, pool, "aacaller", "pw", true)
	target := seedUser(t, pool, "aatarget", "pw", false)

	body := `{"auto_approve":true}`
	req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/auto-approve",
		bytes.NewReader([]byte(body)))
	req = withUser(req, admin)
	rec := httptest.NewRecorder()
	newAdminUsersRouter(h).ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	var resp adminUserView
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if !resp.AutoApproveRequests {
		t.Errorf("auto_approve_requests = false on response; expected true")
	}

	// Verify DB.
	var aa bool
	if err := pool.QueryRow(context.Background(),
		"SELECT auto_approve_requests FROM users WHERE id = $1", target.ID).Scan(&aa); err != nil {
		t.Fatalf("verify: %v", err)
	}
	if !aa {
		t.Errorf("DB row not updated")
	}
}
