# frozen_string_literal: true

module ReleaseTools
  module Deployments
    # Tracking of deployments using the GitLab API
    class DeploymentTracker
      include ::SemanticLogger::Loggable
      include ReleaseTools::Tracker::Deployment

      # The name of the staging-canary environment of GitLab.com.
      ENVIRONMENT = 'gstg-cny'

      # environment - The name of the environment that was deployed to.
      # status - The status of the deployment, such as "success" or "failed".
      # version - The raw deployment version, as passed from the deployer.
      def initialize(version:, environment: nil, status: nil)
        @environment = environment
        @status = status
        @version = version
      end

      def commit_range
        current, previous = GitlabClient
          .deployments(
            Project::GitlabEe.auto_deploy_path,
            ENVIRONMENT,
            status: 'success'
          )
          .first(2)
          .map(&:sha)

        if previous && current
          [previous, current]
        else
          []
        end
      end

      private

      attr_reader :environment, :status, :version

      def perform_checks
        check_status
      end

      def versions
        gitlab_version = product_version['gitlab-ee']
        omnibus_version = product_version['omnibus-gitlab-ee']
        gitaly_version = product_version['gitaly']
        kas_version = product_version['gitlab_kas']

        log_parsed_versions(
          GitLab: gitlab_version,
          Omnibus: omnibus_version,
          Gitaly: gitaly_version,
          Kas: kas_version
        )

        [
          [Project::GitlabEe, gitlab_version],
          [Project::OmnibusGitlab, omnibus_version],
          [Project::Gitaly, gitaly_version],
          [Project::Kas, kas_version]
        ]
      end

      def log_parsed_versions(components_version)
        components_version.each do |component, version|
          logger.info(
            "Parsed #{component} version from #{@version}",
            sha: version.sha,
            ref: version.ref,
            is_tag: version.tag?
          )
        end
      end
    end
  end
end
