/*
 * Copyright (C) 2026 Fluxer Contributors
 *
 * This file is part of Fluxer.
 *
 * Fluxer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Fluxer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
 */

package integration

import (
	"fmt"
	"net/http"
	"testing"
	"time"
)

// TestAuthIPAuthorizationTokenSingleUse validates that an IP authorization
// token can only be used once and becomes invalid after successful use.
func TestAuthIPAuthorizationTokenSingleUse(t *testing.T) {
	client := newTestClient(t)
	originalIP := client.clientIP

	email := fmt.Sprintf("ip-single-use-%d@example.com", time.Now().UnixNano())
	password := uniquePassword()

	registerTestUser(t, client, email, password)
	clearTestEmails(t, client)

	newIP := "10.100.101.102"
	if newIP == originalIP {
		newIP = "10.100.101.103"
	}
	clientFromNewIP := &testClient{
		baseURL:    client.baseURL,
		httpClient: client.httpClient,
		clientIP:   newIP,
	}

	loginReq := loginRequest{
		Email:    email,
		Password: password,
	}

	resp, err := clientFromNewIP.postJSON("/auth/login", loginReq)
	if err != nil {
		t.Fatalf("failed to trigger IP authorization: %v", err)
	}
	resp.Body.Close()

	emailData := waitForEmail(t, client, "ip_authorization", email)
	authToken := emailData.Metadata["token"]

	resp, err = clientFromNewIP.postJSON("/auth/authorize-ip", map[string]string{"token": authToken})
	if err != nil {
		t.Fatalf("failed to authorize IP first time: %v", err)
	}
	if resp.StatusCode != http.StatusNoContent {
		body := readResponseBody(resp)
		t.Fatalf("expected first authorization to succeed, got %d: %s", resp.StatusCode, body)
	}
	resp.Body.Close()

	resp, err = clientFromNewIP.postJSON("/auth/authorize-ip", map[string]string{"token": authToken})
	if err != nil {
		t.Fatalf("failed to attempt second authorization: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusNoContent || resp.StatusCode == http.StatusOK {
		t.Fatalf("expected token reuse to be rejected, got success status %d", resp.StatusCode)
	}

	if resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusBadRequest && resp.StatusCode != http.StatusGone {
		body := readResponseBody(resp)
		t.Fatalf("expected token reuse to return 401, 400, or 410, got %d: %s", resp.StatusCode, body)
	}
}
