package delima

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestClientNotConfigured(t *testing.T) {
	c := New("", "")
	if c.Configured() {
		t.Fatal("should not be configured")
	}
	if _, err := c.User(context.Background(), "a@b.com"); !errors.Is(err, ErrNotConfigured) {
		t.Fatalf("expected ErrNotConfigured, got %v", err)
	}
}

func TestUserParsesNumericIDAndNullOrg(t *testing.T) {
	payload := `{"id":12345,"email":"m-1@moe-dl.edu.my","role":{"text":"student"},"organization":null,"classroom":{"code":"1A","name":"Satu A"}}`
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("X-DELIMA-TOKEN") != "tok" {
			t.Errorf("missing token header")
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(payload))
	}))
	defer srv.Close()

	c := New(srv.URL, "tok")
	u, err := c.User(context.Background(), "m-1@moe-dl.edu.my")
	if err != nil {
		t.Fatal(err)
	}
	if u.ID.String() != "12345" {
		t.Fatalf("id = %q", u.ID.String())
	}
	if u.Organization != nil {
		t.Fatal("expected nil organization")
	}
	if u.Classroom == nil || u.Classroom.Code != "1A" {
		t.Fatalf("classroom = %+v", u.Classroom)
	}
}

func TestUserParsesStringID(t *testing.T) {
	payload := `{"id":"abc","email":"x@y.com","role":{"text":"admin"},"organization":{"code":"S1","state":"Johor","district":"JB"}}`
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		_, _ = w.Write([]byte(payload))
	}))
	defer srv.Close()

	u, err := New(srv.URL, "tok").User(context.Background(), "x@y.com")
	if err != nil {
		t.Fatal(err)
	}
	if u.ID.String() != "abc" {
		t.Fatalf("id = %q", u.ID.String())
	}
	if u.Organization == nil || u.Organization.Code != "S1" {
		t.Fatalf("org = %+v", u.Organization)
	}
}

func TestUserNotFound(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		_, _ = w.Write([]byte(`{"email":""}`))
	}))
	defer srv.Close()

	if _, err := New(srv.URL, "tok").User(context.Background(), "x@y.com"); !errors.Is(err, ErrUserNotFound) {
		t.Fatalf("expected ErrUserNotFound, got %v", err)
	}
}
