package health

import (
	"context"
	"time"

	"hyapp-admin-server/internal/repository"
)

type RedisHealth interface {
	Ping(context.Context) error
}

type JobStatusProvider interface {
	Status() map[string]any
}

type HealthService struct {
	store   *repository.Store
	redis   RedisHealth
	jobs    JobStatusProvider
	timeout time.Duration
}

func NewService(store *repository.Store, redis RedisHealth, jobs JobStatusProvider, timeout time.Duration) *HealthService {
	return &HealthService{store: store, redis: redis, jobs: jobs, timeout: timeout}
}

func (s *HealthService) Health() map[string]any {
	return map[string]any{"status": "ok"}
}

func (s *HealthService) Ready(ctx context.Context) (map[string]any, error) {
	ctx, cancel := context.WithTimeout(ctx, s.timeout)
	defer cancel()

	status := map[string]any{"status": "ready", "dependencies": map[string]any{}}
	deps := status["dependencies"].(map[string]any)
	if err := s.store.Ping(); err != nil {
		deps["mysql"] = "down"
		return status, err
	}
	deps["mysql"] = "ok"
	if s.redis != nil {
		if err := s.redis.Ping(ctx); err != nil {
			deps["redis"] = "down"
			return status, err
		}
		deps["redis"] = "ok"
	}
	if s.jobs != nil {
		deps["jobs"] = s.jobs.Status()
	}
	return status, nil
}
