class Api::V1::Organizations::SyncRepositoriesController < Api::V1::BaseController
  before_action :load_organization, only: [:create]

  def create 
    return render_error("请输入正确的外部组织login") unless params[:external_login].present?
    # 拉取外部组织仓库列表
    url = URI("https://api.github.com/orgs/#{params[:external_login]}/repos?page=#{params[:page]}&per_page=#{params[:limit]}")
    https = Net::HTTP.new(url.host, url.port)
    https.use_ssl = true
    request = Net::HTTP::Get.new(url)
    request["Authorization"] = "Bearer #{params[:external_token]}"
    response = https.request(request)
    if response.code == "200"
      repos = JSON.parse(response.body)
      repos.each do |repo|
        # 检查是否已经存在该仓库
        @project = @organization.projects.find_by(identifier: repo["name"])
        if @project.present?
          if @project.repository.mirror.failed?
            @project.destroy! 
            mirror_params = {name: repo["name"], user_id: @organization.id, description: repo["description"], repository_name: repo["name"], auth_token: params[:external_token], clone_addr: repo["clone_url"]}
            @project = ::Projects::MigrateService.call(current_user, mirror_params)
          end
          @project.update_column(:created_on, repo['created_at'].to_time)
          @project.update_column(:updated_on, repo['updated_at'].to_time)
          next
        else
          mirror_params = {name: repo["name"], user_id: @organization.id, description: repo["description"], repository_name: repo["name"], auth_token: params[:external_token], clone_addr: repo["clone_url"]}
          @project = ::Projects::MigrateService.call(current_user, mirror_params)
          @project.update_column(:created_on, repo['created_at'].to_time)
          @project.update_column(:updated_on, repo['updated_at'].to_time)
        end
      end
    end
  end

  private
  def sync_repository_params
    params.permit(:external_token)
  end

end