defmodule ApiWeb.Redirect do
  use ApiWeb, :controller
  alias Api.Repo
  import Ecto.Query
  require Logger


   def index(conn, %{"accession" => accession}) do
    Envar.load(".env")
    Envar.require_env_file(".env")

    redirect = Envar.get("REDIRECT")
     
    idsite = Envar.get("IDSITE")
    Logger.info("parametros: #{inspect(accession)}")
    
   
    if redirect == "TRUE"  do
      hash = case get_hash_v2(accession) do
         {:ok, hash} ->
             
          url = "https://estudio.informemedico.com.ar/#/#{idsite}/" <> hash
          
        {:error, error_msg} ->
        text(conn, "Error al obtener hash: #{error_msg}")
        
         end
       redirect(conn, external: hash)
      else
        text(conn, "Error 404")
     end
   end

   defp get_hash_v2(accession) do
   
     hash = ApiWeb.GetHash.get_hash(accession)
     if hash == "nil" do
       {:error, "Estudio no encontrado"}
     else
       {:ok, hash}
     end
   end

end


