defmodule Api.Downloadpdf do
  import Ecto.Query
  alias Api.Repo
  require Logger

  def get_report_query(idstudyreport) do
    Logger.info("hash antes de query: #{idstudyreport}")
    #  uso hex en la desencriptación porque el proceso de encriptación involucraba convertir los datos binarios a una cadena de texto (substring)
    q = """
    SELECT convert_from(decrypt(decode('#{idstudyreport}', 'hex')::bytea, '1nf0rm3'::bytea, 'aes'), 'UTF8');
    """
    idstudyreport = Repo.query!(q).rows |> hd() |> hd()
    Logger.info("hash despues de query: #{idstudyreport}")

    idstudyreport = String.to_integer(idstudyreport)

    template_name = Envar.get("TEMPLATE_NAME")
    # template_name = System.get_env("TEMPLATE_NAME")
    Logger.info("template: #{template_name}")
    # pr2_statusname = Envar.get("pr2_statusname")

    query =
    from sr in "studyreport",
      join: s in "study",
      on: s.idstudy == sr.idstudy,
      join: p in "patient",
      on: p.idpatient == s.idpatient,
      left_join: pr in "professional",
      on: pr.idprofessional == sr.idprofessional_finalizedby,
      left_join: u in "users",
      on: u.iduser == pr.iduser,
      join: pt in "printtemplates",
      on: pt.printtemplate_type == "STUDYREPORT",
      where: sr.idstudyreport == ^idstudyreport,
      where: pt.printtemplate == ^template_name,
      where: pt.enabled == true,
      select: %{
        idstudyreport: sr.idstudyreport,
        body: sr.body,
        idstudy: s.idstudy,
        printtemplate: pt.template,
        accessionnumber: s.accessionnumber,
        patientname: fragment("replace(?, '^', ' ')", p.patientname),
        studydate: fragment("TO_CHAR(?, 'YYYY-MM-DD')", s.studydate),
        studytime: s.studytime,
        studydescription: fragment("COALESCE(?, '')", s.studydescription),
        proceduredescription: fragment("COALESCE(?, '')", s.proceduredescription),
        procedurecode: fragment("COALESCE(?, '')", s.procedurecode),
        modality: s.modality,
        patientid: p.patientid,
        patientbirthdate: fragment("TO_CHAR(?, 'YYYY-MM-DD')", p.patientbirthdate),
        fin_signature: fragment("COALESCE(?, '')", pr.signature),
        matricula_finalized: fragment("COALESCE(?, '')", pr.matricula),
        informantphysician: u.username,
        insurer: fragment("COALESCE(?, '')", s.insurer),
        institutionname: fragment("COALESCE(?, '')", s.institutionname),
        referringphysiciansname: fragment("COALESCE(?, '')", s.referringphysiciansname)
        # servicio: fragment("COALESCE(?, '')", s.servicio)
      }


    result = Repo.one(
      from q in subquery(query),
      select: fragment("json_build_object('idstudyreport', ?, 'body', ?, 'idstudy', ?, 'accessionnumber', ?, 'patientname', ?, 'studydate', ?, 'studytime', ?, 'studydescription', ?, 'proceduredescription', ?, 'procedurecode', ?, 'modality', ?, 'patientid', ?, 'patientbirthdate', ?, 'fin_signature', ?, 'matricula_finalized', ?, 'informantphysician', ?, 'insurer', ?, 'institutionname', ?, 'referringphysiciansname', ?, 'printtemplate', ?)",
        q.idstudyreport, q.body, q.idstudy, q.accessionnumber, q.patientname, q.studydate, q.studytime, q.studydescription, q.proceduredescription, q.procedurecode, q.modality, q.patientid, q.patientbirthdate, q.fin_signature, q.matricula_finalized, q.informantphysician, q.insurer, q.institutionname, q.referringphysiciansname, q.printtemplate
      )
    )
    Logger.info("#{inspect(result)}")
    result
  end
end
