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

  # El token fue generado con generate_token(%{password: "1nf0rm3"})
  @valid_token "XHhlNmU3Y2RmYjAyOGZhNWM5NjVhZGNkOTNhOTQ0NDRkYmYwMWFkM2U3YjQ1NjE1YzU1ZDg0ZjlmMDQzNDRmNTUw"


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

    if not valid_token?(conn) do
      conn
      |> put_status(:unauthorized)
      |> json(%{error: "Token inválido o ausente"})
    else

      Logger.info("Accession get hash -> #{accessionnumber}")
        hash = get_hash(accessionnumber)
        if hash == "nil" do
      
          conn
          |> put_status(:not_found)
          |> json(%{error: "Estudio no encontrado"})
        else
        
          conn
          |> put_status(:ok)
          |> json(%{hash: hash})

        end
    end
  end

    def get_hash(accessionnumber) do

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

      # En caso de recibir idstudy en get hash -> where: s.accessionnumber == ^String.to_integer(accessionnumber),

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

      case Repo.one(query) do
        nil ->
          "nil"
        res ->
          vencimiento = DateTime.add(DateTime.utc_now(), 2 * 24 * 60 * 60, :second)

          json_data = Map.put(res, :vencimiento, vencimiento)

          token = generate_token(json_data)

      end

  end


  def generate_token(json) do
    json_string = Jason.encode!(json)
    query = "select encrypt('#{json_string}'::bytea, '1nf0rm3', 'aes')::text"
    token = Repo.query!(query).rows |> hd() |> hd()

    token = Base.encode64(token)
    token
  end

 defp valid_token?(conn) do
    case get_req_header(conn, "authorization") do
      ["Bearer " <> token] -> token == @valid_token
      _ -> false
    end
  end


end
