//go:build integration

package admin_test

import (
	"testing"

	"github.com/ultisuite/ulti-backend/internal/integrationtest"
)

func TestAdminUsers(t *testing.T) {
	h := integrationtest.RequireHarness(t)
	adminClient, _ := integrationtest.RequireAdminClient(t, h)

	externalID := integrationtest.NewExternalID("managed")
	createResp, err := adminClient.Post("/api/v1/admin/users", map[string]string{
		"external_id": externalID,
		"email":       externalID + "@example.com",
		"name":        "Managed User",
	})
	integrationtest.FailIf(err, t, "create user")
	integrationtest.FailUnlessStatus(t, createResp, 201)

	var created map[string]any
	integrationtest.DecodeJSON(t, createResp, &created)
	userID, _ := created["id"].(string)
	if userID == "" {
		t.Fatalf("missing user id: %#v", created)
	}

	listResp, err := adminClient.Get("/api/v1/admin/users")
	integrationtest.FailIf(err, t, "list users")
	integrationtest.FailUnlessStatus(t, listResp, 200)

	getResp, err := adminClient.Get("/api/v1/admin/users/" + userID)
	integrationtest.FailIf(err, t, "get user")
	integrationtest.FailUnlessStatus(t, getResp, 200)

	disableResp, err := adminClient.Post("/api/v1/admin/users/"+userID+"/disable", nil)
	integrationtest.FailIf(err, t, "disable user")
	integrationtest.FailUnlessStatus(t, disableResp, 204)

	reactResp, err := adminClient.Post("/api/v1/admin/users/"+userID+"/reactivate", nil)
	integrationtest.FailIf(err, t, "reactivate user")
	integrationtest.FailUnlessStatus(t, reactResp, 204)
}

func TestNonAdminForbidden(t *testing.T) {
	h := integrationtest.RequireHarness(t)
	userClient, _ := integrationtest.RequireUserClient(t, h)

	resp, err := userClient.Get("/api/v1/admin/users")
	integrationtest.FailIf(err, t, "list users as non-admin")
	if resp.Status != 403 {
		t.Fatalf("status = %d, want 403", resp.Status)
	}
}
