package handlers

import (
	"database/sql"
	"encoding/json"
	"net/http"
	"os"

	ory "github.com/ory/client-go"
)

func sqlNullString(s string) sql.NullString {
	if s == "" {
		return sql.NullString{}
	}
	return sql.NullString{String: s, Valid: true}
}

func nullStringToString(ns sql.NullString) string {
	if ns.Valid {
		return ns.String
	}
	return ""
}

func sqlNullUUID(s string) sql.NullString {
	if s == "" {
		return sql.NullString{}
	}
	return sql.NullString{String: s, Valid: true}
}

func writeJSON(w http.ResponseWriter, v interface{}) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(v)
}

func getOryAPIURL() string {
	oryAPIURL := os.Getenv("ORY_API_URL")
	if oryAPIURL == "" {
		tunnelPort := os.Getenv("TUNNEL_PORT")
		if tunnelPort == "" {
			tunnelPort = "4000"
		}
		oryAPIURL = "http://localhost:" + tunnelPort
	}
	return oryAPIURL
}

func isAuthenticated(r *http.Request, oryClient *ory.APIClient) bool {
	cookies := r.Header.Get("Cookie")
	session, _, err := oryClient.FrontendAPI.ToSession(r.Context()).Cookie(cookies).Execute()
	if err != nil {
		return false
	}
	return session != nil && session.Active != nil && *session.Active
}
