class SendinblueWebhooksController < ApplicationController
  # You can configure webhook for this controller at https://app-smtp.sendinblue.com/webhook
  def rgpd_contact_error
    sendinblue_api_key = ENV["SENDINBLUE_API_KEY"]
    capability_url_id = ENV["RGPD_CONTACT_ERROR_HOOK_ID"]

    # 1. verify capability url id
    if params[:capability_url_id] != capability_url_id
      raise ApplicationController::AccessDenied, ""
    end

    # 2. get message metadata
    body = JSON.parse request.body.read
    message_id = body["message-id"]
    get_transactional_email_reponse = Http.get(
      "https://api.sendinblue.com/v3/smtp/emails?messageId=#{URI.encode(message_id)}",
      sendinblue_api_key,
      "Sendinblue API v3",
      "api-key"
    )
    transactional_email = get_transactional_email_reponse.parse

    # 3. exit if email was not about notifying rgpd contacts
    if transactional_email.empty? ||
        transactional_email["transactionalEmails"].length != 1 ||
        (transactional_email["transactionalEmails"][0]["tags"][0]["rgpd-contact-email"] != "rgpd-contact-email")
      # Note that there is no need to check that the event is an hard bounce or a soft bounce since this hook will be
      # called on this to events only.
      raise ApplicationController::Accepted, "no gdpr alert send"
    end

    email_uuid = transactional_email["transactionalEmails"][0]["uuid"]
    rgpd_contact_email = transactional_email["transactionalEmails"][0]["email"]
    rgpd_role = transactional_email["transactionalEmails"][0]["subject"][/(#{EnrollmentsController::RESPONSABLE_TRAITEMENT_LABEL}|#{EnrollmentsController::DPO_LABEL})/, 1]

    # 4. get email content
    get_email_content_response = Http.get(
      "https://api.sendinblue.com/v3/smtp/emails/#{email_uuid}",
      sendinblue_api_key,
      "Sendinblue API v3",
      "api-key"
    )
    email_content = get_email_content_response.parse

    enrollment_id = email_content["body"][/https:\/\/datapass(-[a-z]+)?.api.gouv.fr\/[a-z-]+\/([0-9]+)/, 2]

    enrollment = Enrollment.find(enrollment_id.to_i)
    instructor_email = enrollment.events.where(name: "validated")[0].user["email"]

    # 5. notify enrollment owner that he made an error with the provided rgpd email
    RgpdMailer.with(
      target_api: enrollment[:target_api],
      to: enrollment.user[:email],
      enrollment_id: enrollment[:id],
      rgpd_role: rgpd_role,
      rgpd_contact_email: rgpd_contact_email,
      instructor_email: instructor_email
    ).rgpd_contact_error.deliver_now

    render status: :ok, json: {
      message: "gdpr alert sent!"
    }
  end
end
