package daemon

import (
	"context"
	"errors"
	"io"
	"net"
	"net/http"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"git.cloudinit.dev/coreci/orca/internal/store"
)

func TestServerLifecycle(t *testing.T) {
	db, err := store.Open(filepath.Join(t.TempDir(), "lifecycle.db"))
	if err != nil {
		t.Fatalf("open db: %v", err)
	}
	defer db.Close()

	s := NewServer(Options{DB: db, Addr: "127.0.0.1:0"})
	s.MarkReady()

	if !s.Ready() {
		t.Error("expected server ready after MarkReady")
	}
	s.MarkNotReady()
	if s.Ready() {
		t.Error("expected server not ready after MarkNotReady")
	}
	s.MarkReady()

	// Bind an ephemeral listener and serve on it directly.
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("listen: %v", err)
	}
	addr := ln.Addr().String()

	errCh := make(chan error, 1)
	go func() {
		err := s.httpServer.Serve(ln)
		if err != nil && !errors.Is(err, http.ErrServerClosed) {
			errCh <- err
		}
		close(errCh)
	}()

	// Verify healthz responds.
	deadline := time.Now().Add(2 * time.Second)
	for time.Now().Before(deadline) {
		c := http.Client{Timeout: 200 * time.Millisecond}
		r, err := c.Get("http://" + addr + "/healthz")
		if err == nil {
			_ = r.Body.Close()
			if r.StatusCode == 200 {
				break
			}
		}
		time.Sleep(20 * time.Millisecond)
	}

	resp, err := http.Get("http://" + addr + "/healthz")
	if err != nil {
		t.Fatalf("GET /healthz: %v", err)
	}
	if resp.StatusCode != 200 {
		t.Errorf("expected 200, got %d", resp.StatusCode)
	}
	body, _ := io.ReadAll(resp.Body)
	_ = resp.Body.Close()
	if !strings.Contains(string(body), `"alive"`) {
		t.Errorf("expected alive status in body, got %s", string(body))
	}

	// readyz returns 200 when ready.
	resp, err = http.Get("http://" + addr + "/readyz")
	if err != nil {
		t.Fatalf("GET /readyz: %v", err)
	}
	if resp.StatusCode != 200 {
		t.Errorf("expected 200, got %d", resp.StatusCode)
	}
	_ = resp.Body.Close()

	// /v1/jobs returns JSON
	resp, err = http.Get("http://" + addr + "/v1/jobs")
	if err != nil {
		t.Fatalf("GET /v1/jobs: %v", err)
	}
	if resp.StatusCode != 200 {
		t.Errorf("expected 200, got %d", resp.StatusCode)
	}
	if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
		t.Errorf("expected JSON content-type, got %s", ct)
	}
	_ = resp.Body.Close()

	// /v1/nodes returns JSON
	resp, err = http.Get("http://" + addr + "/v1/nodes")
	if err != nil {
		t.Fatalf("GET /v1/nodes: %v", err)
	}
	if resp.StatusCode != 200 {
		t.Errorf("expected 200, got %d", resp.StatusCode)
	}
	_ = resp.Body.Close()

	// /v1/tasks returns JSON
	resp, err = http.Get("http://" + addr + "/v1/tasks")
	if err != nil {
		t.Fatalf("GET /v1/tasks: %v", err)
	}
	if resp.StatusCode != 200 {
		t.Errorf("expected 200, got %d", resp.StatusCode)
	}
	_ = resp.Body.Close()

	// Shutdown cleanly.
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		t.Errorf("shutdown: %v", err)
	}
	if s.Ready() {
		t.Error("expected not-ready after shutdown")
	}

	// Server should report ErrServerClosed or nil.
	select {
	case err := <-errCh:
		if err != nil && !errors.Is(err, http.ErrServerClosed) {
			t.Errorf("expected nil or ErrServerClosed, got %v", err)
		}
	case <-time.After(2 * time.Second):
		t.Error("server did not exit after Shutdown")
	}
}

func TestIsShutdownErr(t *testing.T) {
	if !IsShutdownErr(http.ErrServerClosed) {
		t.Error("expected IsShutdownErr(http.ErrServerClosed) to be true")
	}
	if IsShutdownErr(errors.New("other")) {
		t.Error("expected false for other errors")
	}
}
