package handlers

import (
	"context"
	"net/http"
	"time"

	"github.com/labstack/echo/v4"
	"gorm.io/gorm"
)

func Healthz() echo.HandlerFunc {
	return func(c echo.Context) error {
		return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
	}
}

func Readyz(appDB, prestaDB *gorm.DB, proxyTarget string) echo.HandlerFunc {
	return func(c echo.Context) error {
		ctx, cancel := context.WithTimeout(c.Request().Context(), 2*time.Second)
		defer cancel()

		if err := pingDB(ctx, appDB); err != nil {
			return echo.NewHTTPError(http.StatusServiceUnavailable, "app db unavailable")
		}
		if err := pingDB(ctx, prestaDB); err != nil {
			return echo.NewHTTPError(http.StatusServiceUnavailable, "prestashop db unavailable")
		}
		if proxyTarget == "" {
			return echo.NewHTTPError(http.StatusServiceUnavailable, "prestashop proxy target unavailable")
		}

		return c.JSON(http.StatusOK, map[string]string{"status": "ready"})
	}
}

func pingDB(ctx context.Context, db *gorm.DB) error {
	sqlDB, err := db.DB()
	if err != nil {
		return err
	}
	return sqlDB.PingContext(ctx)
}
