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

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

    redirect_flag = Envar.get("REDIRECT")
    viewer = Envar.get("imViewer4")
    viewer_host = Envar.get("imViewer4_host")
    viewer_uid = Envar.get("imViewer4_uid")
    gethash = Envar.get("imViewer4_gethash")
    idsite = Envar.get("IDSITE")

    Logger.info("parametros: #{inspect(accession)}")

    if redirect_flag == "TRUE" do
      case viewer do
        # Nuevo viewer imViewer4
        "1" ->
          viewer_config = %{
            client_uuid: viewer_uid,
            gethash: gethash,
            imviewer4_domain: viewer_host
          }

          case open_imviewer4(viewer_config, accession, 172800) do
            {:ok, hash} ->
              url = "https://#{viewer_host}/imviewer4/viewer/#{viewer_uid}/#{hash}"
              Logger.info("Redirect -> #{url}")
              redirect(conn, external: url)

            {:error, reason} ->
              Logger.error("No se pudo obtener hash: #{inspect(reason)}")
              text(conn, "Error al obtener hash: #{inspect(reason)}")
          end

        # Viewer viejo
        "0" ->
          case get_hash_v2(accession) do
            {:ok, hash} ->
              url = "https://estudio.informemedico.com.ar/#/#{idsite}/" <> hash
              Logger.info("Redirect -> #{url}")
              redirect(conn, external: url)

            {:error, error_msg} ->
              text(conn, "Error al obtener hash: #{error_msg}")
          end

        # Default / mal configurado
        _ ->
          text(conn, "Error: configuración de viewer inválida")
      end
    else
      text(conn, "Error 404")
    end
  end

  # ---- Helpers ----
  defp get_hash_v2(accession) do
    Logger.info("parametros:\n #{inspect(accession)}")
    hash = ApiWeb.GetHash.get_hash(accession)

    if hash == "nil" do
      {:error, "Estudio no encontrado"}
    else
      {:ok, hash}
    end
  end

  defp open_imviewer4(v, accession, expiration) do
    url = v.gethash <> v.client_uuid

      studyidentifier = Envar.get("IDENTIFIERFIELD") || "IDSTUDY"

      query =
        if studyidentifier == "IDSTUDY" do
          from s in "study",
            where: s.accessionnumber == ^accessionnumber,
            select: %{
              idstudy: s.idstudy
            }
        else
          from s in "study",
            where: s.accessionnumber == ^accessionnumber,
            select: %{
              idstudy: s.idstudy
            }
        end

      idstudy = case Repo.one(query) do
        nil ->
          "nil"
        res ->
          res.idstudy
      end

    idstudy_str = to_string(idstudy)

    case Req.post(url, json: %{"idstudy" => idstudy_str, "expiration" => expiration}) do
      {:ok, %Req.Response{status: 200, body: %{"hash" => hash}}} ->
        {:ok, hash}

      {:ok, %Req.Response{status: status, body: body}} ->
        {:error, {:unexpected_response, status, body}}

      {:error, reason} ->
        {:error, {:request_failed, reason}}
    end
  end
end
