package tests

import (
	"encoding/json"
	"testing"
)

func TestAuth(t *testing.T) {
	// Ensure base users are created (Admin, User1, User2)
	ensureUsers(t)

	// Test Temp User Lifecycle
	tempUser := "temp_user"
	tempPass := "password123"
	tempEmail := "temp@test.com"

	// 1. Register Temp User
	t.Run("Register Temp User", func(t *testing.T) {
		resp := doRequest(t, "POST", "/api/auth/register", map[string]string{
			"username": tempUser,
			"password": tempPass,
			"email":    tempEmail,
		}, "")

		// If user exists from previous run, that's fine, but in clean run it should be 200
		if resp.Code != 200 {
			var r struct {
				Code int `json:"code"`
			}
			json.Unmarshal(resp.Body.Bytes(), &r)
			if r.Code != 40003 && r.Code != 40001 {
				t.Errorf("Expected 40003 or 40001, got %d", r.Code)
			}
		} else {
			assertStatus(t, resp, 200)
		}
	})

	// 2. Login Temp User
	var tempToken string

	t.Run("Login Temp User", func(t *testing.T) {
		resp := doRequest(t, "POST", "/api/auth/login", map[string]string{
			"username": tempUser,
			"password": tempPass,
		}, "")
		assertStatus(t, resp, 200)
		t.Logf("Login Response: %s", resp.Body.String())

		var data LoginResp
		decodeResponse(t, resp, &data)
		tempToken = data.AccessToken
	})

	if tempToken == "" {
		t.Fatal("Failed to get temp token, skipping remaining auth tests")
	}

	// 3. Get User Info
	t.Run("Get Temp User Info", func(t *testing.T) {
		resp := doRequest(t, "GET", "/api/auth/me", nil, tempToken)
		assertStatus(t, resp, 200)

		var data UserResp
		decodeResponse(t, resp, &data)
	})

	// 4. Update User Info (using /api/auth/me for regular users)
	t.Run("Update Temp User Info", func(t *testing.T) {
		resp := doRequest(t, "PATCH", "/api/auth/me", map[string]string{
			"nickname": "Temp Nickname",
		}, tempToken)
		assertStatus(t, resp, 200)
	})

	// 5. Logout
	t.Run("Logout Temp User", func(t *testing.T) {
		resp := doRequest(t, "POST", "/api/auth/logout", map[string]interface{}{}, tempToken)
		assertStatus(t, resp, 200)
	})

	// 6. Verify Token Invalid after Logout (Optional, depends on implementation)
	// If logout blacklist is implemented, this should fail with 401
}
