package grpchealth

import (
	"context"
	"errors"
	"testing"

	healthpb "google.golang.org/grpc/health/grpc_health_v1"
)

func TestServingCheckerMapsReadiness(t *testing.T) {
	checker := NewServingChecker("wallet-service")
	server := NewServer(checker)

	resp, err := server.Check(context.Background(), &healthpb.HealthCheckRequest{Service: "wallet-service"})
	if err != nil {
		t.Fatalf("Check before serving failed: %v", err)
	}
	if resp.GetStatus() != healthpb.HealthCheckResponse_NOT_SERVING {
		t.Fatalf("status before serving mismatch: got %s want NOT_SERVING", resp.GetStatus())
	}

	checker.MarkServing()
	resp, err = server.Check(context.Background(), &healthpb.HealthCheckRequest{Service: "wallet-service"})
	if err != nil {
		t.Fatalf("Check after serving failed: %v", err)
	}
	if resp.GetStatus() != healthpb.HealthCheckResponse_SERVING {
		t.Fatalf("status after serving mismatch: got %s want SERVING", resp.GetStatus())
	}

	checker.MarkDraining()
	resp, err = server.Check(context.Background(), &healthpb.HealthCheckRequest{Service: "wallet-service"})
	if err != nil {
		t.Fatalf("Check after draining failed: %v", err)
	}
	if resp.GetStatus() != healthpb.HealthCheckResponse_NOT_SERVING {
		t.Fatalf("status after draining mismatch: got %s want NOT_SERVING", resp.GetStatus())
	}
}

func TestServingCheckerDependencyFailureAffectsReady(t *testing.T) {
	checker := NewServingChecker("wallet-service", Dependency{
		Name: "mysql",
		Check: func(context.Context) error {
			return errors.New("mysql down")
		},
	})
	checker.MarkServing()

	checks := checker.Ready(context.Background())
	if Healthy(checks) {
		t.Fatalf("dependency failure should make checker not ready: %+v", checks)
	}
}
