class Api::V1::Projects::Actions::RunsController < Api::V1::Projects::Actions::BaseController

  def index
    @files = $gitea_client.get_repos_contents_by_owner_repo_filepath(@project&.owner&.login, @project&.identifier, ".gitea/workflows") rescue []
    @has_file = @files.select { |i| i['name'] == params[:workflow] }.present?
    if @has_file
      @result_object = Api::V1::Projects::Actions::Runs::ListService.call(@project, {workflow: params[:workflow], page: page, limit: limit}, current_user&.gitea_token)
      @begin_num = (page.to_i - 1) * limit.to_i
    end
  end

  def create 
    return render_error("请输入正确的流水线文件！") if params[:workflow].blank? 
    return render_error("请输入正确的分支！") if params[:ref].blank? 
    gitea_result = $gitea_hat_client.post_repos_actions_runs_by_owner_repo(@project&.owner&.login, @project&.identifier, {query: {workflow: params[:workflow], ref: params[:ref]}})
    if gitea_result
      render_ok 
    else 
      ender_error("启动流水线任务失败")
    end  
  end

  def rerun 
    return render_error("请输入正确的流水线记录ID！") if params[:run_id].blank?
    gitea_result = $gitea_hat_client.post_repos_actions_runs_rerun_by_owner_repo_run(@project&.owner&.login, @project&.identifier, params[:run_id]) rescue nil 
    if gitea_result
      render_ok 
    else 
      render_error("重启所有流水线任务失败")
    end
  end

  def job_rerun 
    return render_error("请输入正确的流水线记录ID！") if params[:run_id].blank?
    return render_error("请输入正确的流水线任务ID") if params[:job].blank? 
    gitea_result = $gitea_hat_client.post_repos_actions_runs_jobs_rerun_by_owner_repo_run_job(@project&.owner&.login, @project&.identifier, params[:run_id], params[:job]) rescue nil 
    if gitea_result
      render_ok 
    else 
      render_error("重启流水线任务失败")
    end
  end

  def job_show 
    @result_object = Api::V1::Projects::Actions::Runs::JobShowService.call(@project, params[:run_id], params[:job], params[:log_cursors], current_user&.gitea_token)
  end

  def job_logs 
    return render_error("请输入正确的流水线记录ID！") if params[:run_id].blank?
    return render_error("请输入正确的流水线任务ID") if params[:job].blank? 
    domain  = GiteaService.gitea_config[:domain]
    api_url = GiteaService.gitea_config[:hat_base_url]

    url = "/repos/#{@owner.login}/#{@repository.identifier}/actions/runs/#{CGI.escape(params[:run_id])}/jobs/#{CGI.escape(params[:job])}/logs"
    file_path = [domain, api_url, url].join
    file_path = [file_path, "access_token=#{@owner&.gitea_token}"].join("?") 

    redirect_to file_path
  end

  def cancel
    return render_error("请输入正确的流水线记录ID！") if params[:run_id].blank?
    http = Gitea::Api::Hat::Http.new($gitea_hat_client.config)
    gitea_result = http.post("/repos/#{@project&.owner&.login}/#{@project&.identifier}/actions/runs/#{params[:run_id]}/cancel") rescue nil
    if gitea_result
      render_ok
    else
      render_error("停止流水线任务失败")
    end
  end

end