# frozen_string_literal: true

module ReleaseTools
  module Security
    module Publish
      # Verifies that the blog post merge request has been successfully merged
      # Only should be called after DeployBlogPost has been called
      class VerifyBlogPost
        include ReleaseTools::Security::MergeRequestHelper
        include ::SemanticLogger::Loggable

        PendingMergeError = Class.new(StandardError)

        # canonical_blog_merge_request returns opened/pending merge requests with label "patch release post"
        # if there are no pending mrs, it means that the blog post mr has been merged already
        def initialize
          @pending_blog_post_mr = canonical_blog_merge_request
        end

        def execute
          verify_blog_post_mr

          send_slack_notification(:success)
        rescue StandardError => ex
          logger.fatal(error_message, error: ex) if ex.is_a?(PendingMergeError)
          send_slack_notification(:failed)

          raise
        end

        private

        attr_reader :pending_blog_post_mr

        def verify_blog_post_mr
          if pending_blog_post_mr.nil?
            logger.info('Blog post has been merged')
          else
            logger.info('Blog post has not been merged', pending_blog_post_mr: pending_blog_post_mr.web_url)

            raise PendingMergeError
          end
        end

        def send_slack_notification(status)
          ReleaseTools::Slack::ReleaseJobEndNotifier.new(
            job_type: 'Verify blog post',
            status: status,
            release_type: :patch
          ).send_notification
        end

        def error_message
          <<~MSG
            The blog post merge request was not merged successfully, check the merge pipeline associated with:
            #{pending_blog_post_mr.web_url}
            If the pipeline is still running, retry this job later.
            If the pipeline failed, retry the failing job, or manually merge the merge request, then retry this job.
          MSG
        end
      end
    end
  end
end
