# frozen_string_literal: true

module ReleaseTools
  module PatchRelease
    module BlogPost
      # This class is responsible for generating the content for a blog merge request.
      class FileCommit
        include ::SemanticLogger::Loggable
        include Utils

        def initialize(**options)
          @versions = options[:versions]
          @project_path = options[:project_path]
          @source_branch = options[:source_branch]
          @target_branch = options[:target_branch]
          @security_fixes = options[:security_fixes]
        end

        def execute!(blog_content)
          find_or_create_branch!
          create_commit!(blog_content)
        end

        private

        # Indirectly needed for blog_post_filename and create_commit! (see Utils module)
        attr_reader :versions

        # Used to check for the presence of security fixes
        attr_reader :security_fixes

        # Other necessary fields
        attr_reader :project_path, :source_branch, :target_branch

        def find_or_create_branch!
          return if SharedStatus.dry_run?

          Retriable.with_context(:api) do
            GitlabClient.find_or_create_branch(source_branch, target_branch, project_path)
          end
        end

        def create_commit!(blog_content)
          logger.info('Committing blog content', project: project_path, branch: source_branch)

          return if SharedStatus.dry_run?

          message = "Adding #{versions_str} blog post"
          actions = [{
            action: 'create',
            file_path: generate_file_path,
            content: blog_content
          }]

          Retriable.with_context(:api) do
            GitlabClient.create_commit(
              project_path,
              source_branch,
              message,
              actions
            )
          end
        end

        def generate_file_path
          blog_post_filepath = "sites/uncategorized/source/releases/posts"

          [blog_post_filepath, blog_post_filename].join('/')
        end

        def blog_post_filename
          suffix = "gitlab-#{hyphenated_version}-released.html.md"
          return "#{1.day.from_now.to_date}-patch-release-#{suffix}" if security_fixes.present?

          "#{Date.current}-#{suffix}"
        end
      end
    end
  end
end
