class Projects::TransferService < ApplicationService
  attr_accessor :project, :owner, :new_owner, :gitea_repo

  def initialize(project, new_owner)
    @project = project
    @owner = project.owner
    @new_owner = new_owner
  end

  def call
    Rails.logger.info("###### Project transfer_service begin ######")
    ActiveRecord::Base.transaction do
      update_actions
      gitea_update_owner
      update_owner
      update_repo_url
      update_visit_teams
      update_fork_info
      update_fork_pull_request_info
    end

    Rails.logger.info("##### Project transfer_service end ######")

    @project.reload
  end

  private
  def update_owner
    # 转移项目需要移除原来的权限
    project.members.update_all(team_user_id: nil)
    project.members.map{|m| m.destroy! if m.user_id == owner.id || project.member(new_owner.id) || (new_owner.is_a?(Organization) && new_owner.is_member?(m.user_id)) }
    project.update!(user_id: new_owner.id)
    project.set_owner_permission(new_owner)
    project.pinned_projects.destroy_all # 移除原来精选的项目
  end

  def update_actions
    begin
      action_params = { has_actions: false }
      Gitea::Repository::UpdateService.call(owner, project.identifier, action_params)
      project.update action_params
    rescue Exception => e
      Rails.logger.info("##### Project transfer_service, gitea transfer error #{e}")
    end
  end

  def update_repo_url
    project.repository.update!(user_id: new_owner.id, url: @gitea_repo["clone_url"])
  end

  def update_visit_teams
    if new_owner.is_a?(Organization)
      # 为包含组织所有项目的团队创建项目访问权限
      new_owner.build_permit_team_projects!(project.id)
    else
      project.team_projects.each(&:destroy!)
    end
  end

  def update_fork_info
    fork_user = ForkUser.find_by(user_id: @owner.id, fork_project_id: @project.id)
    fork_user.update(user_id: @new_owner.id) if fork_user.present?
  end

  def update_fork_pull_request_info 
    fork_pull_requests = PullRequest.where(fork_project_id: @project.id)
    fork_pull_requests.update_all(fork_project_owner: @new_owner&.login) if fork_pull_requests.present?
  end

  def gitea_update_owner
    begin
      @gitea_repo = $gitea_hat_client.post_repos_transfer_by_owner_repo(owner&.login, project.identifier, {body: {new_owner: new_owner&.login}.to_json})
      # @gitea_repo = Gitea::Repository::TransferService.call(owner&.gitea_token, owner&.login, project.identifier, new_owner&.login)
    rescue Exception => e
      Rails.logger.info("##### Project transfer_service, gitea transfer error #{e}")
    end
  end
end