# frozen_string_literal: true

module ReleaseTools
  module PipelineTracer
    class Job
      FINISHED_STATUSES = %w[success failed canceled].freeze

      # Non bridge jobs that trigger downstream pipelines
      TRIGGER_JOBS = %w[wait:cng wait:omnibus].freeze

      VALID_ENVIRONMENTS = %w[gstg-cny gstg-ref gstg gprd-cny gprd].freeze

      attr_reader :job, :client

      delegate :started_at, :finished_at, :web_url, :status, :name, :id, :stage, :allow_failure, :queued_duration, to: :job

      # @param [Gitlab::ObjectifiedHash] job
      def initialize(job, client)
        @job = job
        @client = client
      end

      def trace
        @trace ||=
          Retriable.with_context(:api) do
            client.job_trace(job.pipeline.project_id, job.id)
          end
      end

      def triggered_pipeline_url
        return @triggered_pipeline_url if defined?(@triggered_pipeline_url)

        @triggered_pipeline_url = nil

        return unless TRIGGER_JOBS.include?(job.name)

        # wait:cng and wait:omnibus jobs
        # Matches log lines of the form:
        # Checking status of pipeline -- {pipeline: "https://dev.gitlab.org/gitlab/omnibus-gitlab/-/pipelines/361107"}
        regex = /Checking status of pipeline -- {.*pipeline.*"(?<pipeline_url>.+)"}$/

        if (match = trace.match(regex))
          @triggered_pipeline_url = match[:pipeline_url]
        end

        @triggered_pipeline_url
      end

      def triggered_downstream_pipeline?
        triggered_pipeline_url.present?
      end

      def completed?
        FINISHED_STATUSES.include?(job.status)
      end

      def real_time_duration
        job.duration
      end

      def environment_from_name
        return @environment_from_name if defined?(@environment_from_name)

        @environment_from_name = VALID_ENVIRONMENTS.detect { |env| job.name.include?(env) }
      end

      def name_without_environment
        return job.name unless environment_from_name

        job.name.sub(environment_from_name, '')
      end

      def root_attributes
        {
          job_name: job.name,
          id: job.id,
          web_url: job.web_url,
          allow_failure: job.allow_failure,
          user: job.user.username,
          stage: job.stage,
          started_at: job.started_at,
          finished_at: job.finished_at,
          status: job.status,
          duration: job.duration,
          queued_duration: job.queued_duration
        }.stringify_keys
      end
    end
  end
end
