package meta

import (
	"context"

	"nadir"
	"nadir/internal/auth"

	"github.com/danielgtaylor/huma/v2"
)

type HealthOutput struct {
	Body struct {
		Status   string `json:"status" example:"ok" doc:"Overall health"`
		Database string `json:"database" example:"ok" doc:"Embedded SQLite session store state"`
		Version  string `json:"version" example:"1.0.0" doc:"Application version"`
	}
}

// RegisterHealth adds a public liveness/readiness probe. It is intentionally
// unauthenticated (no permission metadata) so load balancers and orchestrators
// can reach it. Returns 503 when the SQLite session store is unreachable, so
// probes can key off the status code without parsing the body.
func RegisterHealth(api huma.API, sessions *auth.SessionStore) {
	huma.Register(api, huma.Operation{
		OperationID: "health",
		Method:      "GET",
		Path:        "/api/health",
		Summary:     "Health check",
		Description: "Public liveness/readiness probe. Reports whether the embedded " +
			"SQLite session store is reachable. Returns 503 when it is not.",
		Tags:   []string{"Meta"},
		Errors: []int{503},
	}, func(ctx context.Context, _ *struct{}) (*HealthOutput, error) {
		if err := sessions.Ping(); err != nil {
			return nil, huma.Error503ServiceUnavailable("session database unreachable", err)
		}
		out := &HealthOutput{}
		out.Body.Status = "ok"
		out.Body.Database = "ok"
		out.Body.Version = nadir.Version
		return out, nil
	})
}
