package main

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"
)

// profilTokenKur: profil klasoru, oturum ve bu profile ait bir eslesme (token ozeti) olusturur.
func profilTokenKur(t *testing.T, anahtar, token string) {
	t.Helper()
	d, err := profilKlasoru(anahtar)
	if err != nil {
		t.Fatal(err)
	}
	oturum := `{"kullaniciAdi":"` + anahtar + `","cerezler":[{"Name":"s","Value":"x"}]}`
	if err := os.WriteFile(filepath.Join(d, "oturum.json"), []byte(oturum), 0o600); err != nil {
		t.Fatal(err)
	}
	veri, _ := json.Marshal([]eslesme{{Site: izinliKoken, TokenOzeti: tokenOzeti(token)}})
	if err := os.WriteFile(filepath.Join(d, "eslesmeler.json"), veri, 0o600); err != nil {
		t.Fatal(err)
	}
}

func korumaliKodu(token string) int {
	h := korumali(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
	req := httptest.NewRequest(http.MethodGet, "/x", nil)
	if token != "" {
		req.Header.Set("X-Bridge-Token", token)
	}
	rec := httptest.NewRecorder()
	h(rec, req)
	return rec.Code
}

func TestTokenProfili(t *testing.T) {
	t.Setenv("APPDATA", t.TempDir())
	profilTokenKur(t, "ahmet", "t-ahmet")
	profilTokenKur(t, "ayse", "t-ayse")

	if p, ok := tokenProfili("t-ayse"); !ok || p != "ayse" {
		t.Errorf("t-ayse icin ayse bekleniyordu, %q %v", p, ok)
	}
	if _, ok := tokenProfili("yok"); ok {
		t.Errorf("taninmayan token eslesmemeliydi")
	}
	if _, ok := tokenProfili(""); ok {
		t.Errorf("bos token eslesmemeliydi")
	}
}

func TestKorumaliProfilEslemesi(t *testing.T) {
	t.Setenv("APPDATA", t.TempDir())
	profilTokenKur(t, "ahmet", "t-ahmet")
	profilTokenKur(t, "ayse", "t-ayse")
	etkinTestKur(t, "ahmet")

	// Etkin hesabin token'i, aktif profil secilmemis olsa da kabul edilir (coklu hesap).
	if c := korumaliKodu("t-ahmet"); c != http.StatusOK {
		t.Errorf("etkin profilin token'i 200 bekleniyordu, %d", c)
	}
	// Etkin olmayan (kapali) hesabin token'i 409.
	if c := korumaliKodu("t-ayse"); c != http.StatusConflict {
		t.Errorf("etkin olmayan profilin token'i 409 bekleniyordu, %d", c)
	}
	if c := korumaliKodu("yok"); c != http.StatusUnauthorized {
		t.Errorf("taninmayan token 401 bekleniyordu, %d", c)
	}
	if c := korumaliKodu(""); c != http.StatusUnauthorized {
		t.Errorf("token yoksa 401 bekleniyordu, %d", c)
	}
}
