class Api::V1::Projects::SyncRepositories::UpdateService < ApplicationService

  include ActiveModel::Model
  attr_reader :project, :external_token, :external_repo_address, :sync_repositories
  attr_accessor :sync_repository1, :sync_repository2

  validates :external_repo_address, format: { with: CustomRegexp::URL_REGEX, multiline: true, message: "地址格式不正确" }
  validates :external_token, presence: true

  #Api::V1::Projects::SyncRepositories::UpdateService.call(Project.last, "21,22", {external_repo_address: "https://github.com/viletyy/testdevops.git", external_token:"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"})
  def initialize(project, sync_repository_ids, params)
    @project = project 
    @sync_repositories = SyncRepository.where(project_id: project.id, id: sync_repository_ids.split(","))
    @external_token = params[:external_token]
    @external_repo_address = params[:external_repo_address]
  end

  def call 
    raise Error, errors.full_messages.join(",") unless valid?

    update_sync_repository

  end

  private
  def update_sync_repository
    @sync_repositories.each do |repo|
      Reposync::UpdateRepoAddrService.call(repo&.repo_name, internal_repo_address, internal_token, external_repo_address, external_token)
      repo.update_attributes!({external_repo_address: external_repo_address, external_token: external_token})
    end
  end

  def internal_repo_address
    "#{EduSetting.get("gitlink_repo_domain")}/#{project.owner&.login}/#{project.identifier}.git"
  end

  def internal_token 
    EduSetting.get("gitlink_admin_token")
  end
end