package tests

import (
	"encoding/json"
	"testing"
)

// ensureUsers ensures that the test users exist and tokens are set
func ensureUsers(t *testing.T) {
	if AdminToken != "" {
		return
	}

	// Admin
	adminUser := "admin_test"
	adminPass := "password123"
	adminEmail := "admin@test.com"

	// Try to login first (in case DB persists but memory cleared - unlikely with TestMain cleanup)
	// Or just register and ignore "already exists" error

	// Register Admin
	registerResp := doRequest(t, "POST", "/api/auth/register", map[string]string{
		"username": adminUser,
		"password": adminPass,
		"email":    adminEmail,
	}, "")
	// If 200 or 400 (already exists), proceed to login
	if registerResp.Code != 200 {
		// Verify if it's because user already exists
		var resp struct {
			Code int `json:"code"`
		}
		if err := json.Unmarshal(registerResp.Body.Bytes(), &resp); err != nil {
			t.Fatalf("Failed to unmarshal response: %v", err)
		}
		if resp.Code != 40003 && resp.Code != 40001 {
			t.Errorf("Expected Vigo code 40003 or 40001, got %d", resp.Code)
		}
	}

	// Login Admin
	loginResp := doRequest(t, "POST", "/api/auth/login", map[string]string{
		"username": adminUser,
		"password": adminPass,
	}, "")
	assertStatus(t, loginResp, 200)

	var loginData LoginResp
	decodeResponse(t, loginResp, &loginData)
	AdminToken = loginData.AccessToken
	AdminID = loginData.User.ID

	// Verify me endpoint works (optional, but good for sanity)
	// meResp := doRequest(t, "GET", "/api/auth/me", nil, AdminToken)
	// assertStatus(t, meResp, 200)

	// User1
	user1Name := "user1_test"
	user1Pass := "password123"
	user1Email := "user1@test.com"

	doRequest(t, "POST", "/api/auth/register", map[string]string{
		"username": user1Name,
		"password": user1Pass,
		"email":    user1Email,
	}, "")

	loginResp1 := doRequest(t, "POST", "/api/auth/login", map[string]string{
		"username": user1Name,
		"password": user1Pass,
	}, "")
	assertStatus(t, loginResp1, 200)
	var loginData1 LoginResp
	decodeResponse(t, loginResp1, &loginData1)
	User1Token = loginData1.AccessToken
	User1ID = loginData1.User.ID

	// User2
	user2Name := "user2_test"
	user2Pass := "password123"
	user2Email := "user2@test.com"

	doRequest(t, "POST", "/api/auth/register", map[string]string{
		"username": user2Name,
		"password": user2Pass,
		"email":    user2Email,
	}, "")

	loginResp2 := doRequest(t, "POST", "/api/auth/login", map[string]string{
		"username": user2Name,
		"password": user2Pass,
	}, "")
	assertStatus(t, loginResp2, 200)
	var loginData2 LoginResp
	decodeResponse(t, loginResp2, &loginData2)
	User2Token = loginData2.AccessToken
	User2ID = loginData2.User.ID
}
